def set_basic_auth(self, get): is_open = False if get.open == 'True': is_open = True tips = '_bt.cn' path = 'config/basic_auth.json' ba_conf = None if os.path.exists(path): try: ba_conf = json.loads(public.readFile(path)) except: os.remove(path) if not ba_conf: ba_conf = { "basic_user": public.md5(get.basic_user.strip() + tips), "basic_pwd": public.md5(get.basic_pwd.strip() + tips), "open": is_open } else: if get.basic_user: ba_conf['basic_user'] = public.md5(get.basic_user.strip() + tips) if get.basic_pwd: ba_conf['basic_pwd'] = public.md5(get.basic_pwd.strip() + tips) ba_conf['open'] = is_open public.writeFile(path, json.dumps(ba_conf)) os.chmod(path, 384) public.WriteLog('面板设置', '设置BasicAuth状态为: %s' % is_open) public.writeFile('data/reload.pl', 'True') return public.returnMsg(True, "设置成功!")
def set_basic_auth(self, get): is_open = False if get.open == 'True': is_open = True tips = '_bt.cn' path = 'config/basic_auth.json' ba_conf = None if os.path.exists(path): ba_conf = json.loads(public.readFile(path)) if not ba_conf: ba_conf = { "basic_user": public.md5(get.basic_user.strip() + tips), "basic_pwd": public.md5(get.basic_pwd.strip() + tips), "open": is_open } else: if get.basic_user: ba_conf['basic_user'] = public.md5(get.basic_user.strip() + tips) if get.basic_pwd: ba_conf['basic_pwd'] = public.md5(get.basic_pwd.strip() + tips) ba_conf['open'] = is_open public.writeFile(path, json.dumps(ba_conf)) os.chmod(path, 384) public.WriteLog('P_CONF', 'SET_BASICAUTH_STATUS %s' % is_open) public.writeFile('data/reload.pl', 'True') return public.returnMsg(True, "SET_SUCCESS")
def set_crond(self): try: echo = public.md5(public.md5('renew_lets_ssl_bt')) cron_id = public.M('crontab').where('echo=?', (echo, )).getField('id') import crontab args_obj = public.dict_obj() if not cron_id: cronPath = public.GetConfigValue( 'setup_path') + '/cron/' + echo shell = 'python %s/panel/class/panelLets.py renew_lets_ssl ' % ( self.setupPath) public.writeFile(cronPath, shell) args_obj.id = public.M('crontab').add( 'name,type,where1,where_hour,where_minute,echo,addtime,status,save,backupTo,sType,sName,sBody,urladdress', ("续签Let's Encrypt证书", 'day', '', '0', '10', echo, time.strftime('%Y-%m-%d %X', time.localtime()), 0, '', 'localhost', 'toShell', '', shell, '')) crontab.crontab().set_cron_status(args_obj) else: cron_path = public.get_cron_path() if os.path.exists(cron_path): cron_s = public.readFile(cron_path) if cron_s.find(echo) == -1: public.M('crontab').where('echo=?', (echo, )).setField( 'status', 0) args_obj.id = cron_id crontab.crontab().set_cron_status(args_obj) except: pass
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']: 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.returnMsg(False, "Did not find the key, please close Google verification on the command line and trun on again") 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") 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('-') 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
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' python_bin = public.get_python_bin() 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_bin +" " + public.GetConfigValue('setup_path')+"/panel/script/backup.py path "+param['sName']+" "+str(param['save']), 'site' : head +python_bin+ " " + public.GetConfigValue('setup_path')+"/panel/script/backup.py site "+param['sName']+" "+str(param['save']), 'database': head +python_bin+ " " + public.GetConfigValue('setup_path')+"/panel/script/backup.py database "+param['sName']+" "+str(param['save']), 'logs' : head +python_bin+ " " + 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_bin+ " " + 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_bin+" " + cfile + " path " + param['sName'] + " " + str(param['save']), 'site' : head + python_bin+" " + cfile + " site " + param['sName'] + " " + str(param['save']), 'database': head + python_bin+" " + cfile + " database " + param['sName'] + " " + str(param['save']), 'logs' : head + python_bin+" " + 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_bin+" " + 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
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()
def request_post(self, post): if not (hasattr(post, 'username') or hasattr(post, 'password') or hasattr(post, 'code')): 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']: 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 session['login'] = True session['username'] = userInfo['username'] public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS', (userInfo['username'], public.GetClientIp())) self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') sess_input_path = 'data/session_last.pl' public.writeFile(sess_input_path, str(int(time.time()))) self.set_request_token() self.login_token() return public.returnJson(True, 'LOGIN_SUCCESS'), json_header 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
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) except: pass public.writeFile('/var/bt_setupPath.conf', '/www') public.ExecShell(c) p_file = 'class/panelPlugin.py' if os.path.exists(p_file): py_compile.compile(p_file) if os.path.exists(p_file + 'c'): os.remove(p_file) p_file = 'class/plugin2.so' if os.path.exists(p_file): public.ExecShell("rm -f class/*.so") clean_session()
def password_salt(password, username=None, uid=None): ''' @name 为指定密码加盐 @author hwliang<2020-07-08> @param password string(被md5加密一次的密码) @param username string(用户名) 可选 @param uid int(uid) 可选 @return string ''' global salt if not salt: salt = public.M('users').where('id=?', (uid, )).getField('salt') return public.md5(public.md5(password + '_bt.cn') + salt)
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 web.ctx.session.webserver=='nginx': log='.log' wheres={ 'site' : head + "python " + web.ctx.session.setupPath+"/panel/script/backup.py site "+param['sName']+" "+param['save'], 'database': head + "python " + web.ctx.session.setupPath+"/panel/script/backup.py database "+param['sName']+" "+param['save'], 'logs' : head + "python " + web.ctx.session.setupPath+"/panel/script/logsBackup "+param['sName']+log+" "+param['save'], 'rememory' : head + "/bin/bash " + web.ctx.session.setupPath + '/panel/script/rememory.sh' } if param['backupTo'] != 'localhost': cfile = web.ctx.session.setupPath + "/panel/plugin/" + param['backupTo'] + "/" + param['backupTo'] + "_main.py"; if not os.path.exists(cfile): cfile = web.ctx.session.setupPath + "/panel/script/backup_" + param['backupTo'] + ".py"; wheres={ 'site' : head + "python " + cfile + " site " + param['sName'] + " " + param['save'], 'database': head + "python " + cfile + " database " + param['sName'] + " " + param['save'], 'logs' : head + "python " + web.ctx.session.setupPath+"/panel/script/logsBackup "+param['sName']+log+" "+param['save'], 'rememory' : head + "/bin/bash " + web.ctx.session.setupPath + '/panel/script/rememory.sh' } try: shell=wheres[type] except: if type == 'toUrl': shell = head + "curl -sS --connect-timeout 10 -m 60 '" + param.urladdress+"'"; else: shell=head+param['sBody'] shell += ''' echo "----------------------------------------------------------------------------" endDate=`date +"%Y-%m-%d %H:%M:%S"` echo "★[$endDate] Successful" echo "----------------------------------------------------------------------------" ''' cronPath=web.ctx.session.setupPath+'/cron' if not os.path.exists(cronPath): public.ExecShell('mkdir -p ' + cronPath); cronName=public.md5(public.md5(str(time.time()) + '_bt')) file = cronPath+'/' + cronName public.writeFile(file,self.CheckScript(shell)) public.ExecShell('chmod 750 ' + file) return cronName except Exception,ex: return public.returnMsg(False, 'FILE_WRITE_ERR')
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' wheres={ 'site' : head + "python " + web.ctx.session.setupPath+"/panel/script/backup.py site "+param['sName']+" "+param['save'], 'database': head + "python " + web.ctx.session.setupPath+"/panel/script/backup.py database "+param['sName']+" "+param['save'], 'logs' : head + "python " + web.ctx.session.setupPath+"/panel/script/logsBackup "+param['sName']+log+" "+param['save'], 'rememory' : head + "/bin/bash " + web.ctx.session.setupPath + '/panel/script/rememory.sh' } if param['backupTo'] != 'localhost': cfile = web.ctx.session.setupPath + "/panel/plugin/" + param['backupTo'] + "/" + param['backupTo'] + "_main.py"; if not os.path.exists(cfile): cfile = web.ctx.session.setupPath + "/panel/script/backup_" + param['backupTo'] + ".py"; wheres={ 'site' : head + "python " + cfile + " site " + param['sName'] + " " + param['save'], 'database': head + "python " + cfile + " database " + param['sName'] + " " + param['save'], 'logs' : head + "python " + web.ctx.session.setupPath+"/panel/script/logsBackup "+param['sName']+log+" "+param['save'], 'rememory' : head + "/bin/bash " + web.ctx.session.setupPath + '/panel/script/rememory.sh' } try: shell=wheres[type] except: if type == 'toUrl': shell = head + "curl -sS --connect-timeout 10 -m 60 '" + param.urladdress+"'"; else: shell=head+param['sBody'] shell += ''' echo "----------------------------------------------------------------------------" endDate=`date +"%Y-%m-%d %H:%M:%S"` echo "★[$endDate] Successful" echo "----------------------------------------------------------------------------" ''' cronPath=web.ctx.session.setupPath+'/cron' if not os.path.exists(cronPath): public.ExecShell('mkdir -p ' + cronPath); cronName=public.md5(public.md5(str(time.time()) + '_bt')) file = cronPath+'/' + cronName public.writeFile(file,self.CheckScript(shell)) public.ExecShell('chmod 750 ' + file) return cronName except Exception,ex: return public.returnMsg(False, 'FILE_WRITE_ERR')
def create_serverid(self, get): userPath = 'data/userInfo.json' if not os.path.exists(userPath): return public.returnMsg(False, '请先登陆宝塔官网用户') tmp = public.readFile(userPath) data = json.loads(tmp) if not data: return public.returnMsg(False, '请先登陆宝塔官网用户') if not hasattr(data, 'serverid'): s1 = self.get_mac_address() + self.get_hostname() s2 = self.get_cpuname() serverid = public.md5(s1) + public.md5(s2) data['serverid'] = serverid public.writeFile(userPath, json.dumps(data)) return data
def checkSafe(self): mods = [ '/', '/site', '/ftp', '/database', '/plugin', '/soft', '/public' ] if not os.path.exists('/www/server/panel/data/userInfo.json'): if 'vip' in web.ctx.session: del (web.ctx.session.vip) if not web.ctx.path in mods: return True if 'vip' in web.ctx.session: return True import uuid, json, panelAuth token = 'data/' + public.md5( uuid.UUID(int=uuid.getnode()).hex[-12:]) + '.pl' # data = panelAuth.panelAuth().get_order_status(None); data = {'status': True, 'msg': {'endtime': 32503651199}} try: if not data: if os.path.exists(token): web.ctx.session.vip = json.loads(public.readFile(token)) return True try: if data['status'] == True: web.ctx.session.vip = data public.writeFile(token, json.dumps(data)) return True except: web.ctx.session.vip = json.loads(public.readFile(token)) return True except: return True raise web.seeother('/vpro') return False
def create_serverid(self,get): try: userPath = 'data/userInfo.json'; if not os.path.exists(userPath): return public.returnMsg(False,'请先登陆宝塔官网用户'); tmp = public.readFile(userPath); if len(tmp) < 2: tmp = '{}' data = json.loads(tmp); if not data: return public.returnMsg(False,'请先登陆宝塔官网用户'); if not hasattr(data,'serverid'): s1 = self.get_mac_address() + self.get_hostname() s2 = self.get_cpuname(); serverid = public.md5(s1) + public.md5(s2); data['serverid'] = serverid; public.writeFile(userPath,json.dumps(data)); return data; except: return public.returnMsg(False,'请先登陆宝塔官网用户');
def _set_login_session(self, userInfo): try: session['login'] = True session['username'] = userInfo['username'] session['uid'] = userInfo['id'] session['login_user_agent'] = public.md5( request.headers.get('User-Agent', '')) public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS', (userInfo['username'], public.GetClientIp() + ":" + str(request.environ.get('REMOTE_PORT')))) self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') session['session_timeout'] = time.time( ) + public.get_session_timeout() self.set_request_token() self.login_token() login_type = 'data/app_login.pl' if os.path.exists(login_type): os.remove(login_type) return public.returnJson(True, 'LOGIN_SUCCESS'), json_header except Exception as ex: stringEx = str(ex) if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1: public.ExecShell("rm -f /tmp/sess_*") public.ExecShell("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
def install(): if public.M('config').where("id=?", ('1', )).getField('status') == 1: if os.path.exists('install.pl'): os.remove('install.pl') return redirect('/login') ret_login = os.path.join('/', admin_path) if admin_path == '/' or admin_path == '/bt': ret_login = '******' if request.method == method_get[0]: if not os.path.exists('install.pl'): return redirect(ret_login) data = {} data['status'] = os.path.exists('install.pl') data['username'] = public.GetRandomString(8).lower() return render_template('install.html', data=data) elif request.method == method_post[0]: if not os.path.exists('install.pl'): return redirect(ret_login) get = get_input() if not hasattr(get, 'bt_username'): return '用户名不能为空!' if not get.bt_username: return '用户名不能为空!' if not hasattr(get, 'bt_password1'): return '密码不能为空!' if not get.bt_password1: return '密码不能为空!' if get.bt_password1 != get.bt_password2: return '两次输入的密码不一致,请重新输入!' public.M('users').where("id=?", (1, )).save( 'username,password', (get.bt_username, public.md5(get.bt_password1.strip()))) os.remove('install.pl') public.M('config').where("id=?", ('1', )).setField('status', 1) data = {} data['status'] = os.path.exists('install.pl') data['username'] = get.bt_username return render_template('install.html', data=data)
def _check(self, get): token_data = public.readFile(self.app_path + 'token.pl') if not token_data: token_data = public.readFile(self.app_path_p + 'token.pl') if hasattr(SelfModule, get['fun']): return False elif get['fun'] in ['set_login', 'is_scan_ok', 'login_qrcode']: return True elif get['fun'] == 'blind': if not token_data: return public.returnMsg(False, 'QRCORE_EXPIRE', ("1", )) token_data = token_data.replace('\n', '') password, expiration_time = token_data.split(':') # return True if time.time() - int(expiration_time) > 8 * 60: return public.returnMsg(False, 'QRCORE_EXPIRE', ("2", )) elif get['panel_token'] != password: return public.returnMsg(False, 'SK_NOT_INCORRECT') return True else: # 是否在白名单ip sgin 是否正确 if hasattr(get, 'uid') and hasattr(get, 'sgin') and hasattr( get, 'fun') and get['uid'] in self.user_info.keys(): encryption_str = self.user_info[ get['uid']]['token'] + get['fun'] + get['uid'] if sys.version_info[0] == 3: if type(encryption_str) == str: encryption_str = encryption_str.encode() if get['sgin'] == public.md5( binascii.hexlify(base64.b64encode(encryption_str))): if public.GetClientIp() in ['47.52.194.186']: return True return public.returnMsg(False, 'UNAUTHORIZED')
def create_serverid(self,get): try: userPath = 'data/userInfo.json' if not os.path.exists(userPath): return public.returnMsg(False,'LOGIN_FIRST') tmp = public.readFile(userPath) if len(tmp) < 2: tmp = '{}' data = json.loads(tmp) if not data: return public.returnMsg(False,'LOGIN_FIRST') if not 'serverid' in data: s1 = self.get_mac_address() + self.get_hostname() s2 = self.get_cpuname() serverid = public.md5(s1) + public.md5(s2) data['serverid'] = serverid public.writeFile(userPath,json.dumps(data)) return data except: return public.returnMsg(False,'LOGIN_FIRST')
def set_token(self, get): if 'request_token' in get: return public.returnMsg(False, 'CANT_SET_API_WIFTH_API') save_path = '/www/server/panel/config/api.json' data = json.loads(public.ReadFile(save_path)) if get.t_type == '1': token = public.GetRandomString(32) data['token'] = public.md5(token) public.WriteLog('SET_API', 'REGENERATE_API_TOKEN') elif get.t_type == '2': data['open'] = not data['open'] stats = { True: public.GetMsg("TURN_ON"), False: public.GetMsg("CLOSE") } public.WriteLog('SET_API', 'API_INTERFACE', (stats[data['open']], )) token = stats[data['open']] + public.GetMsg("SUCCESS") elif get.t_type == '3': data['limit_addr'] = get.limit_addr.split('\n') public.WriteLog('SET_API', 'CHANGE_IP_LIMIT', (get.limit_addr)) token = public.GetMsg("SAVE_SUCCESS") public.WriteFile(save_path, json.dumps(data)) return public.returnMsg(True, token)
def _check(self, get): token_data = public.readFile(self.app_path + 'token.pl') if not token_data: token_data = public.readFile(self.app_path_p + 'token.pl') if hasattr(SelfModule, get['fun']): return False elif get['fun'] in ['set_login', 'is_scan_ok', 'login_qrcode']: return True elif get['fun'] == 'blind': if not token_data: return public.returnMsg(False, '二维码过期!') token_data = token_data.replace('\n', '') password, expiration_time = token_data.split(':') # return True if time.time() - int(expiration_time) > 8 * 60: return public.returnMsg(False, '二维码过期!') elif get['panel_token'] != password: return public.returnMsg(False, '秘钥不正确!') return True else: # 是否在白名单ip sgin 是否正确 if hasattr(get, 'uid') and hasattr(get, 'sgin') and hasattr( get, 'fun') and get['uid'] in self.user_info.keys(): encryption_str = self.user_info[ get['uid']]['token'] + get['fun'] + get['uid'] if get['sgin'] == public.md5( binascii.hexlify(base64.b64encode(encryption_str))): if get['client_ip'] in [ '118.24.150.167', '103.224.251.67', '125.88.182.170', '47.52.194.186', '39.104.53.226', '119.147.144.162' ]: return True return public.returnMsg(False, '未授权!')
def request_temp(self, get): try: if not hasattr(get, 'tmp_token'): return public.getMsg('INIT_ARGS_ERR') if len(get.tmp_token) != 48: return public.getMsg('INIT_ARGS_ERR') if not re.match(r"^\w+$", get.tmp_token): return public.getMsg('INIT_ARGS_ERR') skey = public.GetClientIp() + '_temp_login' if not public.get_error_num(skey, 10): return public.getMsg('AUTH_FAILED') s_time = int(time.time()) data = public.M('temp_login').where( 'state=? and expire>?', (0, s_time)).field('id,token,salt,expire').find() if not data: public.set_error_num(skey) return public.getMsg('VERIFICATION_FAILED') if not isinstance(data, dict): public.set_error_num(skey) return public.getMsg('VERIFICATION_FAILED') r_token = public.md5(get.tmp_token + data['salt']) if r_token != data['token']: public.set_error_num(skey) return public.getMsg('VERIFICATION_FAILED') public.set_error_num(skey, True) userInfo = public.M('users').where( "id=?", (1, )).field('id,username').find() session['login'] = True session['username'] = public.getMsg('TEMPORARY_ID', (data['id'], )) session['tmp_login'] = True session['tmp_login_id'] = str(data['id']) session['tmp_login_expire'] = time.time() + 3600 session['uid'] = data['id'] sess_path = 'data/session' if not os.path.exists(sess_path): os.makedirs(sess_path, 384) public.writeFile(sess_path + '/' + str(data['id']), '') login_addr = public.GetClientIp() + ":" + str( request.environ.get('REMOTE_PORT')) public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS', (userInfo['username'], login_addr)) public.M('temp_login').where('id=?', (data['id'], )).update({ "login_time": s_time, 'state': 1, 'login_addr': login_addr }) self.limit_address('-') cache.delete('panelNum') cache.delete('dologin') sess_input_path = 'data/session_last.pl' public.writeFile(sess_input_path, str(int(time.time()))) self.set_request_token() self.login_token() self.set_cdn_host(get) return redirect('/') except: return public.getMsg('LOGIN_FAIL')
def ToDataBase(self, find): #if find['username'] == 'bt_default': return 0 if len(find['password']) < 3: find['username'] = find['name'] find['password'] = public.md5(str(time.time()) + find['name'])[0:10] public.M('databases').where("id=?", (find['id'], )).save( 'password,username', (find['password'], find['username'])) result = panelMysql.panelMysql().execute("create database `" + find['name'] + "`") if "using password:"******"Connection refused" in str(result): return -1 password = find['password'] #if find['password']!="" and len(find['password']) > 20: #password = find['password'] self.__CreateUsers(find['name'], find['username'], password, find['accept']) #panelMysql.panelMysql().execute("drop user '" + find['username'] + "'@'localhost'") #panelMysql.panelMysql().execute("drop user '" + find['username'] + "'@'" + find['accept'] + "'") #panelMysql.panelMysql().execute("grant all privileges on " + find['name'] + ".* to '" + find['username'] + "'@'localhost' identified by '" + password + "'") #panelMysql.panelMysql().execute("grant all privileges on " + find['name'] + ".* to '" + find['username'] + "'@'" + find['accept'] + "' identified by '" + password + "'") #panelMysql.panelMysql().execute("flush privileges") return 1
def get_sk(self): save_path = '/www/server/panel/config/api.json' if not os.path.exists(save_path): return redirect('/login') try: api_config = json.loads(public.ReadFile(save_path)) except: os.remove(save_path) return redirect('/login') if not api_config['open']: return redirect('/login') from BTPanel import get_input get = get_input() client_ip = public.GetClientIp() if not 'client_bind_token' in get: if not 'request_token' in get or not 'request_time' in get: return redirect('/login') num_key = client_ip + '_api' if not public.get_error_num(num_key,20): return public.returnJson(False,'AUTH_FAILED1') if not client_ip in api_config['limit_addr']: public.set_error_num(num_key) return public.returnJson(False,'%s[' % public.GetMsg("AUTH_FAILED1")+client_ip+']') else: num_key = client_ip + '_app' if not public.get_error_num(num_key,20): return public.returnJson(False,'AUTH_FAILED1') a_file = '/dev/shm/' + get.client_bind_token if not os.path.exists(a_file): import panelApi if not panelApi.panelApi().get_app_find(get.client_bind_token): public.set_error_num(num_key) return public.returnJson(False,'UNBOUND_DEVICE') public.writeFile(a_file,'') if not 'key' in api_config: public.set_error_num(num_key) return public.returnJson(False, 'KEY_ERR') if not 'form_data' in get: public.set_error_num(num_key) return public.returnJson(False, 'FORM_DATA_ERR') g.form_data = json.loads(public.aes_decrypt(get.form_data, api_config['key'])) get = get_input() if not 'request_token' in get or not 'request_time' in get: return redirect('/login') g.is_aes = True g.aes_key = api_config['key'] request_token = public.md5(get.request_time + api_config['token']) if get.request_token == request_token: public.set_error_num(num_key,True) return False public.set_error_num(num_key) return public.returnJson(False,'SECRET_KEY_CHECK_FALSE')
def is_login(result): if 'login' in session: if session['login'] == True: result = make_response(result) request_token = public.md5(app.secret_key + str(time.time())) session['request_token'] = request_token result.set_cookie('request_token',request_token,httponly=True,max_age=86400*30) return result
def set_panel_pwd(password): import db sql = db.Sql() result = sql.table('users').where('id=?', (1, )).setField('password', public.md5(password)) username = sql.table('users').where('id=?', (1, )).getField('username') print username
def check_login(self): try: api_check = True g.api_request = False if not 'login' in session: api_check = self.get_sk() if api_check: session.clear() return api_check g.api_request = True else: if session['login'] == False: public.WriteLog('Login auth', 'The current session has been logged out') session.clear() return redirect('/login') if 'tmp_login_expire' in session: s_file = 'data/session/{}'.format(session['tmp_login_id']) if session['tmp_login_expire'] < time.time(): public.WriteLog('Login auth', 'Temporary authorization has expired {}'.format(public.get_client_ip())) session.clear() if os.path.exists(s_file): os.remove(s_file) return redirect('/login') if not os.path.exists(s_file): public.WriteLog('Login auth', 'Forced withdrawal due to cancellation of temporary authorization {}'.format(public.get_client_ip())) session.clear() return redirect('/login') ua_md5 = public.md5(g.ua) if ua_md5 != session.get('login_user_agent',ua_md5): public.WriteLog('Login auth', 'UA verification failed {}'.format(public.get_client_ip())) session.clear() return redirect('/login') if api_check: session_timeout = session.get('session_timeout',0) if session_timeout < time.time() and session_timeout != 0: public.WriteLog('Login auth', 'The session has expired {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=0') login_token = session.get('login_token','') if login_token: if login_token != public.get_login_token_auth(): public.WriteLog('Login auth', 'Session ID does not match {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=1') if api_check: filename = 'data/sess_files/' + public.get_sess_key() if not os.path.exists(filename): public.WriteLog('Login auth', 'Trigger CSRF defense {}'.format(public.get_client_ip())) session.clear() return redirect('/login?dologin=True&go=2') except: public.WriteLog('Login auth',public.get_error_info()) session.clear() return redirect('/login')
def POST(self): post = web.input() web.ctx.session.lan = public.get_language() if not (hasattr(post, 'username') or hasattr(post, 'password') or hasattr(post, 'code')): return public.returnJson(False, 'LOGIN_USER_EMPTY') self.errorNum(False) if self.limitAddress('?') < 1: return public.returnJson(False, 'LOGIN_ERR_LIMIT') 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() if hasattr(web.ctx.session, 'code'): if web.ctx.session.code: if not public.checkCode(post.code): public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_CODE', ('****', web.ctx.session.code, web.ctx.ip)) return public.returnJson(False, 'CODE_ERR') try: if userInfo['username'] != post.username or userInfo[ 'password'] != password: public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS', ('****', '******', web.ctx.ip)) num = self.limitAddress('+') return public.returnJson(False, 'LOGIN_USER_ERR', (str(num), )) import time login_temp = 'data/login.temp' if not os.path.exists(login_temp): public.writeFile( login_temp, '') login_logs = public.readFile(login_temp) public.writeFile( login_temp, login_logs + web.ctx.ip + '|' + str(int(time.time())) + ',') web.ctx.session.login = True web.ctx.session.username = userInfo['username'] public.WriteLog('TYPE_LOGIN', 'LOGIN_SUCCESS', (userInfo['username'], web.ctx.ip)) self.limitAddress('-') numFile = '/tmp/panelNum.pl' timeFile = '/tmp/panelNime.pl' if os.path.exists(numFile): os.remove(numFile) if os.path.exists(timeFile): os.remove(timeFile) return public.returnJson(True, 'LOGIN_SUCCESS') except Exception, ex: stringEx = str(ex) if stringEx.find('unsupported') != -1 or stringEx.find('-1') != -1: btClear() return public.returnJson(False, '磁盘Inode已用完,面板已尝试释放Inode,请重试...') public.WriteLog('TYPE_LOGIN', 'LOGIN_ERR_PASS', ('****', '******', web.ctx.ip)) num = self.limitAddress('+') return public.returnJson(False, 'LOGIN_USER_ERR', (str(num), ))
def basic_auth_check(): if app.config['BASIC_AUTH_OPEN']: if request.path in ['/public','/download']: return; auth = request.authorization if not comm.get_sk(): return; if not auth: return send_authenticated() tips = '_bt.cn' if public.md5(auth.username.strip() + tips) != app.config['BASIC_AUTH_USERNAME'] or public.md5(auth.password.strip() + tips) != app.config['BASIC_AUTH_PASSWORD']: return send_authenticated()
def initUserInfo(): data = public.M('users').where('id=?', (1, )).getField('password') if data == '21232f297a57a5a743894a0e4a801fc3': pwd = public.getRandomString(8).lower() file_pw = public.getRunDir() + '/data/default.pl' public.writeFile(file_pw, pwd) public.M('users').where('id=?', (1, )).setField('password', public.md5(pwd))
def set_panel_pwd(password,ncli = False): import db sql = db.Sql() result = sql.table('users').where('id=?',(1,)).setField('password',public.md5(password)) username = sql.table('users').where('id=?',(1,)).getField('username') if ncli: print("|-用户名: " + username); print("|-新密码: " + password); else: print(username)
def set_panel_pwd(password,ncli = False): import db sql = db.Sql() result = sql.table('users').where('id=?',(1,)).setField('password',public.md5(password)) username = sql.table('users').where('id=?',(1,)).getField('username') if ncli: print("|-%s: " % public.GetMsg("USER_NAME") + username); print("|-%s: " % public.GetMsg("NEW_PASS") + password); else: print(username)
def GetToken(self,get): data = {} data['username'] = get.username; data['password'] = public.md5(get.password); pdata = {} pdata['data'] = self.De_Code(data); result = json.loads(public.httpPost(self.__APIURL+'/GetToken',pdata)); result['data'] = self.En_Code(result['data']); if result['data']: public.writeFile(self.__UPATH,json.dumps(result['data'])); del(result['data']); return result;
def GetServerToken(self,get): password = public.M('users').where('id=?',(1,)).getField('password'); if password != public.md5(get.password): return public.returnMsg(False,'密码验证失败!'); tokenFile = '/www/server/panel/plugin/safelogin/token.pl'; if not os.path.exists(tokenFile): tokenStr = public.GetRandomString(64); public.writeFile(tokenFile,tokenStr); else: tokenStr = public.readFile(tokenFile); public.ExecShell('chattr +i ' + tokenFile); return tokenStr.strip();
def AddDatabase(self,get): try: data_name = get['name'].strip() if self.CheckRecycleBin(data_name): return public.returnMsg(False,'数据库['+data_name+']已在回收站,请从回收站恢复!'); if len(data_name) > 16: return public.returnMsg(False, 'DATABASE_NAME_LEN') reg = "^\w+$" if not re.match(reg, data_name): return public.returnMsg(False,'DATABASE_NAME_ERR_T') if not hasattr(get,'db_user'): get.db_user = data_name; username = get.db_user.strip(); checks = ['root','mysql','test','sys','panel_logs'] if username in checks or len(username) < 1: return public.returnMsg(False,'数据库用户名不合法!'); if data_name in checks or len(data_name) < 1: return public.returnMsg(False,'数据库名称不合法!'); data_pwd = get['password'] if len(data_pwd)<1: data_pwd = public.md5(time.time())[0:8] sql = public.M('databases') if sql.where("name=? or username=?",(data_name,username)).count(): return public.returnMsg(False,'DATABASE_NAME_EXISTS') address = get['address'].strip() user = '******' password = data_pwd codeing = get['codeing'] wheres={ 'utf8' : 'utf8_general_ci', 'utf8mb4' : 'utf8mb4_general_ci', 'gbk' : 'gbk_chinese_ci', 'big5' : 'big5_chinese_ci' } codeStr=wheres[codeing] #添加MYSQL result = panelMysql.panelMysql().execute("create database `" + data_name + "` DEFAULT CHARACTER SET " + codeing + " COLLATE " + codeStr) isError = self.IsSqlError(result) if isError != None: return isError panelMysql.panelMysql().execute("drop user '" + username + "'@'localhost'") panelMysql.panelMysql().execute("drop user '" + username + "'@'" + address + "'") panelMysql.panelMysql().execute("grant all privileges on `" + data_name + "`.* to '" + username + "'@'localhost' identified by '" + data_pwd + "'") for a in address.split(','): panelMysql.panelMysql().execute("grant all privileges on `" + data_name + "`.* to '" + username + "'@'" + a + "' identified by '" + data_pwd + "'") panelMysql.panelMysql().execute("flush privileges") if get['ps'] == '': get['ps']=public.getMsg('INPUT_PS'); addTime = time.strftime('%Y-%m-%d %X',time.localtime()) pid = 0 if hasattr(get,'pid'): pid = get.pid #添加入SQLITE sql.add('pid,name,username,password,accept,ps,addtime',(pid,data_name,username,password,address,get['ps'],addTime)) public.WriteLog("TYPE_DATABASE", 'DATABASE_ADD_SUCCESS',(data_name,)) return public.returnMsg(True,'ADD_SUCCESS') except Exception,ex: public.WriteLog("TYPE_DATABASE",'DATABASE_ADD_ERR', (data_name,str(ex))) return public.returnMsg(False,'ADD_ERROR')
def GET(self): import vilidate,time if hasattr(web.ctx.session,'codeTime'): if (time.time() - web.ctx.session.codeTime) < 0.1: return public.getMsg('CODE_BOOM'); vie = vilidate.vieCode(); codeImage = vie.GetCodeImage(80,4); try: from cStringIO import StringIO except: from StringIO import StringIO out = StringIO(); codeImage[0].save(out, "png") web.ctx.session.codeStr = public.md5("".join(codeImage[1]).lower()) web.ctx.session.codeTime = time.time() web.header('Cache-Control', 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); web.header('Pragma', 'no-cache'); web.header('Content-Type','image/png'); return out.getvalue();
def POST(self): post = web.input() web.ctx.session.lan = public.get_language(); if not (hasattr(post, 'username') or hasattr(post, 'password') or hasattr(post, 'code')): return public.returnJson(False,'LOGIN_USER_EMPTY'); if not self.errorNum(False): return public.returnJson(False,'防暴破机制已被启动,解除命令: rm -f /tmp/panelN*.pl'); if self.limitAddress('?') < 1: return public.returnJson(False,'LOGIN_ERR_LIMIT'); 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() if hasattr(web.ctx.session,'code'): if web.ctx.session.code: if not public.checkCode(post.code): public.WriteLog('TYPE_LOGIN','LOGIN_ERR_CODE',(userInfo['username'],web.ctx.session.code,web.ctx.ip)); return public.returnJson(False,'CODE_ERR'); try: if userInfo['username'] != post.username or userInfo['password'] != password: public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',(userInfo['username'],'******',web.ctx.ip)); num = self.limitAddress('+'); return public.returnJson(False,'LOGIN_USER_ERR',(str(num),)); import time; login_temp = 'data/login.temp' if not os.path.exists(login_temp): public.writeFile(login_temp,''); login_logs = public.readFile(login_temp); public.writeFile(login_temp,login_logs + web.ctx.ip + '|' + str(int(time.time())) + ','); web.ctx.session.login = True; web.ctx.session.username = userInfo['username']; public.WriteLog('TYPE_LOGIN','LOGIN_SUCCESS',(userInfo['username'],web.ctx.ip)); self.limitAddress('-'); numFile = '/tmp/panelNum.pl'; timeFile = '/tmp/panelNime.pl'; if os.path.exists(numFile): os.remove(numFile); if os.path.exists(timeFile): os.remove(timeFile); return public.returnJson(True,'LOGIN_SUCCESS'); except: public.WriteLog('TYPE_LOGIN','LOGIN_ERR_PASS',(userInfo['username'],'******',web.ctx.ip)); num = self.limitAddress('+'); return public.returnJson(False,'LOGIN_USER_ERR',(str(num),));
def ToDataBase(self,find): if find['username'] == 'bt_default': return 0 if len(find['password']) < 3 : find['username'] = find['name'] find['password'] = public.md5(str(time.time()) + find['name'])[0:10] public.M('databases').where("id=?",(find['id'],)).save('password,username',(find['password'],find['username'])) result = panelMysql.panelMysql().execute("create database " + find['name']) if "using password:"******"Connection refused" in str(result): return -1 panelMysql.panelMysql().execute("drop user '" + find['username'] + "'@'localhost'") panelMysql.panelMysql().execute("drop user '" + find['username'] + "'@'" + find['accept'] + "'") password = find['password'] if find['password']!="" and len(find['password']) > 20: password = find['password'] panelMysql.panelMysql().execute("grant all privileges on " + find['name'] + ".* to '" + find['username'] + "'@'localhost' identified by '" + password + "'") panelMysql.panelMysql().execute("grant all privileges on " + find['name'] + ".* to '" + find['username'] + "'@'" + find['accept'] + "' identified by '" + password + "'") panelMysql.panelMysql().execute("flush privileges") return 1
def POST(self): if not os.path.exists('install.pl'): raise web.seeother('/login'); get = web.input(); if not hasattr(get,'bt_username'): return '用户名不能为空!'; if not get.bt_username: return '用户名不能为空!' if not hasattr(get,'bt_password1'): return '密码不能为空!'; if not get.bt_password1: return '密码不能为空!'; if get.bt_password1 != get.bt_password2: return '两次输入的密码不一致,请重新输入!'; public.M('users').where("id=?",(1,)).save('username,password',(get.bt_username,public.md5(get.bt_password1.strip()))) os.remove('install.pl'); data = {} data['status'] = os.path.exists('install.pl'); data['username'] = get.bt_username; render = web.template.render( 'templates/' + templateName + '/',globals={'session': session}); return render.install(data);
def setPassword(self,get): #return public.returnMsg(False,'体验服务器,禁止修改!') if get.password1 != get.password2: return public.returnMsg(False,'USER_PASSWORD_CHECK') if len(get.password1) < 5: return public.returnMsg(False,'USER_PASSWORD_LEN') public.M('users').where("username=?",(web.ctx.session.username,)).setField('password',public.md5(get.password1.strip())) public.WriteLog('TYPE_PANEL','USER_PASSWORD_SUCCESS',(web.ctx.session.username,)) return public.returnMsg(True,'USER_PASSWORD_SUCCESS')
def set_panel_pwd(password): import db sql = db.Sql() result = sql.table('users').where('id=?',(1,)).setField('password',public.md5(password)) username = sql.table('users').where('id=?',(1,)).getField('username') print username;