From 3b263cf8079fb4fc718625a5a07aa61be4545531 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=86=A0=E6=9E=97?= Date: Fri, 25 Jan 2019 16:07:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=97=A5=E5=BF=97=E5=92=8C?= =?UTF-8?q?=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- VPN_CGI/settings.py | 66 +++++++++++++++++++++++-- command/views.py | 115 ++++++++++++++++++++++++++++++-------------- setup.sh | 1 + vpn_cgi.sh | 1 + 4 files changed, 143 insertions(+), 40 deletions(-) diff --git a/VPN_CGI/settings.py b/VPN_CGI/settings.py index aa9575f..e016b08 100644 --- a/VPN_CGI/settings.py +++ b/VPN_CGI/settings.py @@ -14,7 +14,11 @@ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - +LOG_PATH = os.path.join(BASE_DIR, 'log') +# 如果地址不存在,则自动创建log文件夹 +# print(1) +# if os.path.exists(LOG_PATH): +# os.mkdir(LOG_PATH) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ @@ -114,7 +118,61 @@ USE_L10N = True USE_TZ = True -# Static files (CSS, JavaScript, Images) -# https://docs.djangoproject.com/en/2.1/howto/static-files/ - STATIC_URL = '/static/' + +LOGGING = { + # version只能为1,定义了配置文件的版本,当前版本号为1.0 + "version": 1, + # True表示禁用logger + "disable_existing_loggers": False, + # 格式化 + 'formatters': { + 'default': { + 'format': '%(levelno)s %(funcName)s %(module)s %(asctime)s %(message)s' + }, + 'simple': { + 'format': '%(levelno)s %(module)s %(created)s %(message)s' + } + }, + + 'handlers': { + 'error_handlers': { + 'level': 'ERROR', + # 日志文件指定为5M, 超过5m重新命名,然后写入新的日志文件 + 'class': 'logging.handlers.RotatingFileHandler', + # 指定文件大小 + 'maxBytes': 5 * 1024, + # 指定文件地址 + 'filename': os.path.join(LOG_PATH, "error.log"), + 'formatter': 'default' + }, + 'debug_handlers': { + 'level': 'DEBUG', + # 日志文件指定为5M, 超过5m重新命名,然后写入新的日志文件 + 'class': 'logging.handlers.RotatingFileHandler', + # 指定文件大小 + 'maxBytes': 5 * 1024 * 1024, + # 指定文件地址 + 'filename': os.path.join(LOG_PATH, "debug.log"), + 'formatter': 'default' + } + }, + 'loggers': { + 'error': { + 'handlers': ['error_handlers'], + 'level': 'ERROR' + }, + 'debug': { + 'handlers': ['debug_handlers'], + 'level': 'DEBUG' + } + }, + + # 'filters': { + # 'require_debug_true': { + # '()': 'django.utils.log.RequireDebugTrue', + # }, + + # } +} + diff --git a/command/views.py b/command/views.py index efc37bf..7a1bf4c 100644 --- a/command/views.py +++ b/command/views.py @@ -10,6 +10,7 @@ import redis import sys import getopt import os +import logging command_dic={'vpncmd':'vpncmd','server':'/SERVER','password':'/PASSWORD:','cmd':'/CMD','hub':'/HUB:', 'secret':'/SECRET:','retry_interval':'/RETRY_INTERVAL:','group':'/GROUP:','realname':'/REALNAME:','note':'/NOTE:', @@ -28,6 +29,47 @@ response_dic={'miss':'miss parameters.', # "link_id","encap_type","direction","outer_sport","outer_dport","outer_sip",\ # "outer_dip","outer_smac","outer_dmac","inner_smac","inner_dmac",\ # "is_valid","op_time"] +logger_error = logging.getLogger('error') +logger_debug = logging.getLogger('debug') +Error_code={-1:'cannot connect to vpnserver',1:'Connection to the server has failed',2:'The destination server is not a VPN server',3:'The connection has been interrupted', +4:'Protocol error',5:'Connecting client is not a VPN client',6:'User cancel',7:'Specified authentication method is not supported',8:'The HUB does not exist', +9:'Authentication failure',10:'HUB is stopped',11:'Session has been deleted',12:'Access denied',13:'Session times out',14:'Protocol is invalid', +15:'Too many connections',16:'Too many sessions of the HUB',17:'Connection to the proxy server fails',18:'Proxy Error',19:'Failed to authenticate on the proxy server', +20:'Too many sessions of the same user',21:'License error',22:'Device driver error',23:'Internal error',24:'The secure device cannot be opened',25:'PIN code is incorrect', +26:'Specified certificate is not stored',27:'Specified private key is not stored',28:'Write failure',29:'Specified object can not be found',30:'Virtual LAN card with the specified name already exists', +31:'Specified virtual LAN card cannot be created',32:'Specified name of the virtual LAN card is invalid',33:'Unsupported',34:'Account already exists',35:'Account is operating', +36:'Specified account not exist',37:'Account is offline',38:'Parameter is invalid',39:'Error has occurred in the operation of the secure device', +40:'Secure device is not specified',41:'Virtual LAN card in use by account',42:'Virtual LAN card of the account can not be found', +43:'Virtual LAN card of the account is already in use',44:'Virtual LAN card of the account is disabled',45:'Value is invalid',46:'Not a farm controller', +47:'Attempting to connect',48:'Failed to connect to the farm controller',49:'A virtual HUB on farm could not be created',50:'HUB cannot be managed on a farm member', +51:'Accepting only local connections for an empty password',52:'Right is insufficient',53:'Listener can not be found',54:'Listener already exists', +55:'Not a farm member',56:'Encryption algorithm is not supported',57:'HUB already exists',58:'Too many HUBs', +59:'Link already exists',60:'The link can not be created on the server farm',61:'Link is off-line',62:'Protocol is invalid', +63:'Too many users',64:'Too many Groups',65:'Group can not be found',66:'User already exists',67:'Group already exists', +68:'Authentication method of the user is not a password authentication',69:'The user does not exist or the old password is wrong', +73:'Cascade session cannot be disconnected',74:'Not completed configure the connection to the VPN server',75:'It is already online', +76:'It is offline',77:'The certificate is not RSA 1024bit',78:'SecureNAT session cannot be disconnected',79:'SecureNAT works only in stand-alone HUB', +80:'SecureNAT function is not working',81:'Stopped by PacketiX VPN Block',82:'Bridge session can not be disconnected',83:'Bridge function is stopped', +84:'Bridge feature is not supported',85:'Certificate of the destination server can not be trusted',86:'Product code is different', +87:'Version is different',88:'Adding capture device failure',89:'VPN code is different',90:'Capture device can not be found',91:'Layer-3 session cannot be disconnected', +92:'L3 switch of the same already exists',93:'Layer-3 switch can not be found',94:'Name is invalid',95:'Failed to add interface',96:'Failed to delete the interface', +97:'Interface that you specified already exists',98:'Failed to add routing table',99:'Failed to delete the routing table',100:'Routing table entry that you specified already exists', +101:'Time is queer',102:'The Virtual Layer 3 Switch can not be started',103:'Client connection licenses shortage',104:'Bridge connection licenses shortage', +105:'Not Accept on the technical issues',106:'Destination VPN server has expired',107:'Monitor port mode was rejected',108:'Bridge-mode or Routing-mode was rejected', +109:'Client IP address is denied',110:'Too many items',111:'Out of memory',112:'Object already exists',113:'A fatal error occurred',114:'License violation has occurred on the server side', +115:'Server side is not connected to the Internet',116:'License violation occurs on the client side',117:'Command or parameter is invalid',118:'License key is invalid', +119:'There is no valid license for the VPN Server',120:'There is no cluster license',121:'Not trying to connect to a server with the Administrator Pack license', +122:'Not trying to connect to a server with the Administrator Pack license (for .NET)',123:'Destination Beta VPN Server has expired',124:'Branding string of connection limit is different (Authentication on the server side)', +125:'Branding string of connection limit is different (Authentication for client-side)',126:'VPN session is disconnected for a certain period of time has elapsed', +127:'Client ID does not match',128:'Too many created users',129:'Subscription expiration date Is earlier than the build date of the VPN Server', +130:'Many trial license is used continuously',131:'There are multiple servers in the back of a global IP address in the NAT-T connection', +132:'DDNS host key duplicate',133:'Specified DDNS host name already exists',134:'Characters that can not be used for the host name is included', +135:'Host name is too long',136:'Host name is not specified',137:'Host name is too short',138:'Necessary that password is changed',139:'Communication to the dynamic DNS server is disconnected', +140:'The ICMP socket can not be opened',141:'Socket for DNS port can not be opened',142:'OpenVPN server feature is not enabled',143:'It is the type of user authentication that are not supported in the open source version', +144:'Operation on VPN Gate Server is not available',145:'Operation on VPN Gate Client is not available',146:'Can not be stopped if operating within VPN Client mode', +147:'It is a feature that is not supported in the open source version',148:'System is suspending' +} + class Redis: def __init__(self,host,port,index): self.host=host @@ -61,6 +103,7 @@ def command(request): # if username == "" and password = "" : server_pwd,host,port,index,hub_name=readconfig() if request.method=='GET': + logger_debug.debug('request is %s ' % (str(request))) cmd_obj=request.GET.get('cmd_obj',default='server') if cmd_obj=='server': command=request.GET.get('cmd',default=None) @@ -69,7 +112,7 @@ def command(request): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse elif(command=='IpExist'): candidate_ip=request.GET.get('candidate_ip',default=None) # print(candidate_ip) @@ -77,25 +120,25 @@ def command(request): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: rtn_code,outs=IpExist(host,port,candidate_ip,index) my_dict=dict() if(rtn_code==0): my_dict['response']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict['error']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse elif(command=='IpNumGet'): addr_pool_id=request.GET.get('addr_pool_id',default=None) if(addr_pool_id==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: rtn_code,outs=IpNumGet(host,port,addr_pool_id,index) my_dict=dict() @@ -103,18 +146,18 @@ def command(request): my_dict['response']=response_dic['success'] my_dict['num']=rtn_code myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict['error']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse elif(command=='AllIpGet'): addr_pool_id=request.GET.get('addr_pool_id',default=None) if(addr_pool_id==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: rtn_code,outs=AllIpGet(host,port,addr_pool_id,index) my_dict=dict() @@ -122,16 +165,16 @@ def command(request): my_dict['response']=response_dic['success'] my_dict['candidate_ip']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict['error']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse elif(server_ip==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: server_cmd=command_dic['vpncmd']+' '+server_ip+' '+command_dic['server'] # if(command=='ServerPasswordSet'): @@ -192,7 +235,7 @@ def command(request): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: command=hub_cmd+' '+command+' '+user_name+' '+command_dic['group']+group+' '+command_dic['realname']+realname+' '+command_dic['note']+note outs,rtn_code=mysubprocess(command) @@ -203,19 +246,19 @@ def command(request): my_dict=dict() my_dict['response']=response_dic['success'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: command=command=hub_cmd+' '+'UserDelete'+' '+user_name mysubprocess(command) my_dict=dict() - my_dict['error']=response_dic['error'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: my_dict=dict() - my_dict['error']=response_dic['exist'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse # elif(command=='UserRadiusSet'): # user_name=request.GET.get('user_name',default='\'*\'') # alias=request.GET.get('alias',default='none') @@ -227,7 +270,7 @@ def command(request): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: command=hub_cmd+' '+command+' '+user_name+' '+command_dic['password']+user_pwd outs,rtn_code=mysubprocess(command) @@ -235,12 +278,12 @@ def command(request): my_dict=dict() my_dict['response']=response_dic['success'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict=dict() - my_dict['error']=response_dic['error'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse elif(command=='UserList'): command=hub_csv_cmd+' '+command outs,rtn_code=mysubprocess(command) @@ -274,19 +317,19 @@ def command(request): user_dict=dict() my_dict['userlist']=user_list myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict=dict() - my_dict['error']=response_dic['error'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse elif(command=='UserDelete'): user_name=request.GET.get('user_name',default=None) if(user_name==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse else: command=hub_cmd+' '+command+' '+user_name # print(command) @@ -295,12 +338,12 @@ def command(request): my_dict=dict() my_dict['response']=response_dic['success'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict=dict() - my_dict['error']=response_dic['error'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse # elif(command=='IPTable'): # user_name=request.GET.get('user_name',default=None) # if(user_name==None): @@ -317,7 +360,7 @@ def command(request): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + # return myresponse command=hub_csv_cmd+' '+command+' '+user_name outs,rtn_code=mysubprocess(command) if(rtn_code==0): @@ -408,12 +451,11 @@ def command(request): elif(my_dict.get('Number_of_Logins')==None): my_dict['Number_of_Logins']='' myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse + # return myresponse else: my_dict=dict() - my_dict['error']=response_dic['error'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse # elif(command=='LogFileList'): # command=hub_cmd+' '+command # elif(command=='DownloadLogFile'): @@ -427,19 +469,19 @@ def command(request): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse command=hub_cmd+' '+command+' '+user_name+' '+command_dic['name']+policy_name+' '+command_dic['value']+value outs,rtn_code=mysubprocess(command) if(rtn_code==0): my_dict=dict() my_dict['response']=response_dic['success'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') - return myresponse else: my_dict=dict() - my_dict['error']=response_dic['error'] + my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) - return myresponse + + logger_debug.debug('return is %s ' % (str(my_dict))) + return myresponse # elif(command=='AdminOptionSet'): # opt_set=request.GET.get('name',default='max_bitrates_download') # value=request.GET.get('value',default='1000000') @@ -521,6 +563,7 @@ def mysubprocess(command, timeout1 = 6): ssh_process = subprocess.Popen(command, shell=False, stdout = subprocess.PIPE, stderr = subprocess.PIPE, close_fds=True) outs, errs = ssh_process.communicate(timeout = timeout1) except Exception: + logger_debug.debug('cannot connect vpn_server') return "error",-1 else: errs = errs.decode("utf-8") diff --git a/setup.sh b/setup.sh index 2115c62..342407c 100644 --- a/setup.sh +++ b/setup.sh @@ -1,4 +1,5 @@ #!/bin/sh while [[ "1" = "1" ]]; do python3 manage.py runserver 0:8090 + sleep 10 done diff --git a/vpn_cgi.sh b/vpn_cgi.sh index bdca685..9bf3227 100644 --- a/vpn_cgi.sh +++ b/vpn_cgi.sh @@ -1,2 +1,3 @@ killall setup.sh +killall python3 ./setup.sh &> out.file &