def fileshare(): s = request.environ.get('beaker.session') urladdr = dict() # 判断配置文件中url是否合规,合规才提交到界面替换默认url pattern = re.compile( r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' ) result = re.match(pattern, AppServer().getConfValue('fileshare', 'urladdr')) if str(result) == 'None': urladdr['url'] = "1" else: urladdr['url'] = AppServer().getConfValue('fileshare', 'urladdr') return template('fileshare', session=s, msg={}, urladdr=urladdr)
def restore(filename): s = request.environ.get('beaker.session') if filename != "": db_name = AppServer().getConfValue('Databases','MysqlDB') db_user = AppServer().getConfValue('Databases','MysqlUser') db_pass = AppServer().getConfValue('Databases','MysqlPass') db_ip = AppServer().getConfValue('Databases','MysqlHost') db_port = AppServer().getConfValue('Databases','MysqlPort') x,y=cmds.gettuplerst('mysql -h%s -P%s -u%s -p%s %s < %s/backupset/%s' % (db_ip,db_port,db_user,db_pass,db_name,gl.get_value('plgdir'),filename)) if x == 0: msg = {'color':'green','message':u'备份集恢复成功,请重启服务以重新加载数据.'} else: msg = {'color':'red','message':u'备份集恢复失败'} else: msg = {'color':'red','message':u'备份集恢复失败'} return template('backupset',session=s,msg=msg)
def wsapi(): import urlparse,urllib s = request.environ.get('beaker.session') odict = urlparse.parse_qs(urlparse.urlparse('wsapi?%s' % request.environ.get('QUERY_STRING')).query) PassKey = AppServer().getConfValue('wsapi','token') try: if odict['token'][0] != PassKey : msg = {'return':255,'message':'token id error...'} return(template('wsapp.html',msg=msg,session=s)) except: msg = {'return':256,'message':'token id error...'} return(template('wsapp.html',msg=msg,session=s)) try: if odict['otype'][0] == 'ddns': sql = """ update dns_records set data=%s where zone=%s and host=%s and autoupdate='1' and status='1' """ result = writeDb(sql,(odict['data'][0],odict['zone'][0],odict['host'][0])) if result == False: msg = {'return':255,'message':'wsapi get error...'} else: msg = {'return':0,'message':result} else: msg = {'return':255,'message':'system not found otype .'} except: msg = {'return':0,'message':'system not found otype .'} return(template('wsapp.html',msg=msg,session=s))
def do_login(): s = request.environ.get('beaker.session') s['sitename'] = AppServer().getConfValue('site', 'sitename') """用户登陆过程,判断用户帐号密码,保存SESSION""" username = request.forms.get('username').strip() password = request.forms.get('passwd').strip() spass = LoginCls().encode(AppServer().getConfValue('keys', 'pkey'), password) if not username or not password: message = u'帐号或密码不能为空!' return template('login', message=message) m = hashlib.md5() m.update(password) password = m.hexdigest() auth_sql = ''' SELECT id,username,access FROM user WHERE username=%s and password=%s ''' auth_user = readDb(auth_sql, (username, password)) if auth_user: s['webhost'] = request.environ.get('HTTP_HOST') s['clientip'] = request.environ.get('REMOTE_ADDR') s['username'] = username s['skeyid'] = spass s['userid'] = auth_user[0]['id'] s['access'] = auth_user[0]['access'] # session中添加系统环境检测警报 s['admemail'] = '*****@*****.**' s['errnum'] = errnum s['PayInfo'] = AppServer().getPayinfo() s.save() wrtlog('Login', '登录成功', username, s['clientip']) else: clientip = request.environ.get('REMOTE_ADDR') wrtlog('Login', '登录失败', username, clientip) message = u'帐号或密码错误!' return template('login', session=s, message=message) #如果用户是普通用户,返回项目页面 if auth_user[0]['access'] == 0: return redirect('/project') return redirect('/')
def do_login(): s = request.environ.get('beaker.session') s['sitename'] = AppServer().getConfValue('site','sitename') """用户登陆过程,判断用户帐号密码,保存SESSION""" username = request.forms.get('username').strip() passwd = request.forms.get('passwd').strip() if not username or not passwd: message = u'帐号或密码不能为空!' return template('login',message=message) m_encrypt = LoginCls().encode(keys,passwd) auth_sql = ''' SELECT id,username,access FROM user WHERE username=%s and passwd=%s ''' auth_user = readDb(auth_sql,(username,m_encrypt)) if auth_user: s['webhost'] = request.environ.get('HTTP_HOST') s['clientip'] = request.environ.get('REMOTE_ADDR') s['username'] = username s['userid'] = auth_user[0]['id'] s['access'] = auth_user[0]['access'] # session中添加系统环境检测警报 s['admemail'] = '*****@*****.**' s['errnum'] = errnum s['PayInfo'] = AppServer().getPayinfo() s.save() wrtlog('Login','登录成功',username,s['clientip']) else: clientip = request.environ.get('REMOTE_ADDR') wrtlog('Login','登录失败',username,clientip) message = u'帐号或密码错误!' return template('login',message=message,session=s) if auth_user[0]['access'] == 0 : return redirect('/project') return redirect('/')
def getfileshareinfo(path): import chardet from MySQL import readDb s = request.environ.get('beaker.session') ftpuser = s['username'] ftppass = LoginCls().decode(AppServer().getConfValue('keys', 'pkey'), s['skeyid']) sql = """ select listenaddr,listenport,passiveenable,passiveaddr from ftpserv """ result = readDb(sql, ) if int(result[0].get('passiveenable')) == 0: if result[0].get('listenaddr') == "*": servaddr = "127.0.0.1" else: servaddr = result[0].get('listenaddr') else: if result[0].get('passiveaddr') == "*": servaddr = "127.0.0.1" else: servaddr = result[0].get('passiveaddr') try: ftp = FTPHandle(servaddr, int(result[0].get('listenport')), '0', '1') except: newflist = [] return json.dumps(newflist) try: ftp.Login(ftpuser, ftppass) except: newflist = [] return json.dumps(newflist) if path == 'root': flistdict = ftp.getdirs() else: charstr = chardet.detect(path).get('encoding') if str(charstr).lower() != "gbk": try: path = path.decode('utf-8').encode('gbk') except: path = path flistdict = ftp.getdirs(path) ftp.close() newflist = [] for i in flistdict.get('files'): charstr = chardet.detect(i.get('name')).get('encoding') if str(charstr).lower() != "utf-8": try: i['name'] = i.get('name').decode('gbk').encode('utf-8') newflist.append(i) except: continue else: newflist.append(i) return json.dumps(newflist)
def do_upload(): import chardet s = request.environ.get('beaker.session') urladdr = dict() # 判断配置文件中url是否合规,合规才提交到界面替换默认url pattern = re.compile( r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' ) result = re.match(pattern, AppServer().getConfValue('fileshare', 'urladdr')) if str(result) == 'None': urladdr['url'] = "1" else: urladdr['url'] = AppServer().getConfValue('fileshare', 'urladdr') username = s['username'] sql = " SELECT concat(D.vdir,'/',U.vdir) as vdir FROM user as U LEFT OUTER JOIN ftpserv as D ON D.id='1' WHERE U.username=%s " ownftpdir = readDb(sql, (username, ))[0].get('vdir') upload = request.files.get('cv') #为了兼容ftp显示字符,UTF8字符文件名转换为GB2312 if is_chinese(upload.filename) == True: ownftpdir = ownftpdir.encode('GB2312', 'ignore') filename = str(upload.filename).encode('GB2312', 'ignore') else: filename = str(upload.filename) #取消判断文件格式,由JS判断 #name, ext = os.path.splitext(upload.filename) #if ext not in ('.rar','.zip','.bin','.tar','.tgz','.tar.gz','.doc','.docx','.xls','.xlsx','.ppt','.pptx'): # msg = {'color':'red','message':u'文件格式不被允许.请重新上传'} # return template('fileshare',session=s,msg=msg,urladdr=urladdr) cmds.gettuplerst('%s/sbin/mkdir -p %s && chown vftp:vftp %s' % (gl.get_value('wkdir'), ownftpdir, ownftpdir)) try: upload.save('%s/%s' % (ownftpdir, filename)) cmds.getdictrst('chown vftp:vftp %s/%s' % (ownftpdir, filename)) msg = {'color': 'green', 'message': u'文件上传成功'} return template('fileshare', session=s, msg=msg, urladdr=urladdr) except: msg = {'color': 'red', 'message': u'文件上传失败'} return template('fileshare', session=s, msg=msg, urladdr=urladdr)
def do_upload(): import chardet s = request.environ.get('beaker.session') dstdir = request.forms.get('dstdir') charstr = chardet.detect(dstdir).get('encoding') if str(charstr).lower() != "gbk": try: dstdir = dstdir.decode('utf-8').encode('gbk') except: dstdir = dstdir ftpuser = s['username'] ftppass = LoginCls().decode(AppServer().getConfValue('keys', 'pkey'), s['skeyid']) sql = """ select listenaddr,listenport,passiveenable,passiveaddr from ftpserv """ result = readDb(sql, ) if int(result[0].get('passiveenable')) == 0: if result[0].get('listenaddr') == "*": servaddr = "127.0.0.1" else: servaddr = result[0].get('listenaddr') else: if result[0].get('passiveaddr') == "*": servaddr = "127.0.0.1" else: servaddr = result[0].get('passiveaddr') try: ftp = FTPHandle(servaddr, int(result[0].get('listenport')), '0', '1') except: return -1 fname = request.forms.get('fname') if fname: charstr = chardet.detect(fname).get('encoding') if str(charstr).lower() != "gbk": try: fname = fname.decode('utf-8').encode('gbk') except: pass os.system('rm -f /tmp/%s_ftpfile' % ftpuser) softfile = request.POST.get('fdesc') softfile.save('/tmp/%s_ftpfile' % ftpuser, overwrite=True) try: ftp.Login(ftpuser, ftppass) ftp.UpLoadFile("/tmp/%s_ftpfile" % ftpuser, fname, dstdir) ftp.close() except: return -1 os.system('rm -f /tmp/%s_ftpfile' % ftpuser) return 0 else: return -1
def systeminfo(): """系统信息项""" s = request.environ.get('beaker.session') info=dict() info['hostname'] = platform.node() info['kernel'] = platform.platform() info['systime'] = cmds.getdictrst('date +"%Y%m%d %H:%M:%S"').get('result') cmdRun='cat /proc/uptime|awk -F. \'{run_days=$1/86400;run_hour=($1%86400)/3600;run_minute=($1%3600)/60;run_second=$1%60;printf("%d天%d时%d分%d秒",run_days,run_hour,run_minute,run_second)}\'' info['runtime'] = cmds.getdictrst(cmdRun).get('result') info['pyversion'] = platform.python_version() info['memsize'] = cmds.getdictrst('cat /proc/meminfo |grep \'MemTotal\' |awk -F: \'{printf ("%.0fM",$2/1024)}\'|sed \'s/^[ \t]*//g\'').get('result') info['cpumode'] = cmds.getdictrst('grep \'model name\' /proc/cpuinfo |uniq |awk -F : \'{print $2}\' |sed \'s/^[ \t]*//g\' |sed \'s/ \+/ /g\'').get('result') info['v4addr'] = 'Wan: '+netmod.NetIP() info['appversion'] = AppServer().getVersion() """管理日志""" sql = " SELECT id,objtext,objact,objhost,objtime FROM logrecord order by id DESC limit 7 " logdict = readDb(sql,) return template('systeminfo',session=s,info=info,logdict=logdict)
def fileshare(path): s = request.environ.get('beaker.session') # 获取FTP目录列表 ftpuser = s['username'] ftppass = LoginCls().decode(AppServer().getConfValue('keys', 'pkey'), s['skeyid']) sql = """ select listenaddr,listenport,passiveenable,passiveaddr from ftpserv """ result = readDb(sql, ) if int(result[0].get('passiveenable')) == 0: if result[0].get('listenaddr') == "*": servaddr = "127.0.0.1" else: servaddr = result[0].get('listenaddr') else: if result[0].get('passiveaddr') == "*": servaddr = "127.0.0.1" else: servaddr = result[0].get('passiveaddr') try: ftp = FTPHandle(servaddr, int(result[0].get('listenport')), '0', '1') except: newflist = [] msg = {'color': 'red', 'message': u'FTP服务连接失败,请检查FTP配置'} return template('fileshare', session=s, msg=msg, path=path, ftpdirs=[]) try: ftp.Login(ftpuser, ftppass) except: newflist = [] msg = {'color': 'red', 'message': u'FTP服务连接失败,请检查FTP配置'} return template('fileshare', session=s, msg=msg, path=path, ftpdirs=[]) try: flistdict = ftp.getdirs() except: newflist = [] msg = {'color': 'red', 'message': u'目录读取失败,请检查FTP配置'} return template('fileshare', session=s, msg=msg, path=path, ftpdirs=[]) ftp.close() return template('fileshare', session=s, msg={}, path=path, ftpdirs=flistdict.get('dirs'))
# set session options session_opts = { 'session.type': 'file', 'session.cookei_expires': 3600, 'session.data_dir': '/tmp/lnmVPNGVsessions', 'session.auto': True } if __name__ == '__main__': # RUN INIT[bottle reloader=True会导致runDaemonTask执行2次,关闭即可] runDaemonTask() # Reload WEB app = default_app() app = SessionMiddleware(app, session_opts) runListen = AppServer().getConfValue('ServConf', 'runListen') runPort = AppServer().getConfValue('ServConf', 'runPort') runSSL = AppServer().getConfValue('ServConf', 'runSSL') runDebug = AppServer().getConfValue('ServConf', 'runDebug') if runSSL == 'False': run(app=app, host=runListen, port=int(runPort), debug=runDebug, server='gevent') elif runSSL == 'True': certfile = '%s/certs/SSL/server.crt' % pro_path keyfile = '%s/certs/SSL/server-key.pem' % pro_path run(app=app, host=runListen, port=int(runPort),
#!/usr/bin/env python #coding=utf-8 import os, sys, json, re, logging, ConfigParser from bottle import request, route, error, run, default_app from bottle import template, static_file, redirect, abort import bottle, hashlib from MySQL import writeDb, readDb from Functions import AppServer, LoginCls, writeVPNconf, wrtlog from Login import checkLogin, checkAccess import Login keys = AppServer().getConfValue('keys', 'passkey') policylist_sql = " select id,name from vpnpolicy " plylist_result = readDb(policylist_sql, ) @route('/changepasswd') @checkLogin def user(): s = request.environ.get('beaker.session') return template('changepasswd', session=s, msg={}, info={}) @route('/changepasswd', method="POST") @checkLogin def user(): s = request.environ.get('beaker.session') username = s.get('username') oldpwd = request.forms.get("oldpwd")
def login(): """用户登陆""" s = request.environ.get('beaker.session') s['sitename'] = AppServer().getConfValue('site', 'sitename') return template('login', session=s, message='')
def run(self, output_fn, **kwargs): '''处理数据库中的任务队列''' # 引入MySQL配置 from Functions import AppServer db_name = AppServer().getConfValue('Databases', 'MysqlDB') db_user = AppServer().getConfValue('Databases', 'MysqlUser') db_pass = AppServer().getConfValue('Databases', 'MysqlPass') db_ip = AppServer().getConfValue('Databases', 'MysqlHost') db_port = AppServer().getConfValue('Databases', 'MysqlPort') dbconn = 'mysql://%s:%s@%s:%s/%s' % (db_user, db_pass, db_ip, int(db_port), db_name) from MySQL import writeDb # 尝试清空DB数据库中记录的JOB信息 try: sql = """delete from apscheduler_jobs ;""" writeDb(sql, ) except: True # 动态引入任务函数 moduleSrc = 'TaskFunctions' dylib = importlib.import_module(moduleSrc) # 重新加载job队列[两种类型调度器按情况选择] from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor job_defaults = {'max_instances': 1} executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } scheduler = BackgroundScheduler(timezone='Asia/Shanghai', executors=executors, job_defaults=job_defaults) # sqlite or mysql scheduler.add_jobstore('sqlalchemy', url='%s' % dbconn) from MySQL import readDb sql = """ Select id,timedesc from taskconf where status='1' """ result = readDb(sql, ) for taskobject in result: Taskid = 'TaskID_%s' % taskobject.get('id') FunName = 'TaskFunc_%s' % taskobject.get('id') function = getattr(dylib, FunName) cronlist = taskobject.get('timedesc').strip().split(' ') print cronlist if len(cronlist) == 5: scheduler.add_job(func=function, trigger='cron', month=cronlist[4], day=cronlist[3], hour=cronlist[2], minute=cronlist[1], second=cronlist[0], id=Taskid) elif len(cronlist) == 6: scheduler.add_job(func=function, trigger='cron', day_of_week=cronlist[5], month=cronlist[4], day=cronlist[3], hour=cronlist[2], minute=cronlist[1], second=cronlist[0], id=Taskid) else: continue scheduler.start() fd = open(output_fn, 'a') try: dtnow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') line = '\n[%s]: System Starting all Tasks...\n' % dtnow fd.write(line) fd.flush() while 1: pass except KeyboardInterrupt: #捕获键盘ctrl+c,在此脚本中不生效,console下可用 dtnow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') line = '\n[%s]: System Stoping all Tasks, please wait...\n' % dtnow fd.write(line) fd.close() scheduler.shutdown() time.sleep(1) os._exit(0)