from django.shortcuts import render from django.http import HttpResponse import subprocess import shlex import json import configparser import re import redis # from pandas import DataFrame 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:', 'alias':'/ALIAS:','name':'/NAME:','value':'/VALUE:','client':'/CLIENT','username':'/USERNAME:','nicname':'/NICNAME:', 'type':'/TYPE:','start':'/START:','expire':'/EXPIRE:','gw':'/GW:','dns':'/DNS:','dns2':'/DNS2:','domain':'/DOMAIN:', 'log':'/LOG:','mac':'/MAC:','ip':'/IP:','mtu':'/MTU:','tcptimeout':'/TCPTIMEOUT:','udptimeout':'/UDPTIMEOUT:','device':'/DEVICE:', 'l2tp':'/L2TP:','l2tpraw':'/L2TPRAW:','etherip':'/ETHERIP:','psk':'/PSK:','defaulthub':'/DEFAULTHUB:','adminhub':'/ADMINHUB:', 'csv':'/CSV'} response_dic={'miss':'miss parameters.', 'exist':'The user with the specified name already exists on the Virtual Hub.', 'success':'The command completed successfully.', 'not_found':'Object not found.', 'error':'The command execute failed.' } # col_DF=["config_id","addr_pool_id","addr_type","ip_addr","location","mrl_ip",\ # "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 self.port=port self.index=index def connect(self): try: pool = redis.ConnectionPool(host=self.host, port=self.port, db=self.index,decode_responses=True) r = redis.StrictRedis(connection_pool=pool) except redis.RedisError as e:# Exception,e:print(str(e)) # print("Error:"+str(e)) return -1,"Error:"+str(e) # sys.exit(2) try: connect_result=r.ping() except redis.ConnectionError: # print("Error:can not connect to redis server with host:"+self.host+" and port:"+self.port) return -1,"Error:can not connect to redis server with host:"+self.host+" and port:"+self.port # sys.exit(2) else: if connect_result==True: self.r=r return 0,"success" else: # print("Error:Ping the Redis server returns not True, check again.") return -1,"Error:Ping the Redis server returns not True, check again." # sys.exit(2) # http:\\localhost:8090\command?cmd_obj=server&cmd=UserCreate&server_pwd=111111&hub_name=NewHub0&hub_pwd=111111&user_name=*&group=none&realname=none¬e=none # Create your views here. 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) server_ip=request.GET.get('server_ip',default=None) if(command==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # return myresponse elif(command=='IpExist'): candidate_ip=request.GET.get('candidate_ip',default=None) # print(candidate_ip) if(candidate_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 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 else: my_dict['error']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # 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 else: rtn_code,outs=IpNumGet(host,port,addr_pool_id,index) my_dict=dict() if(rtn_code!=-1): my_dict['response']=response_dic['success'] my_dict['num']=rtn_code myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') # return myresponse else: my_dict['error']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # 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 else: rtn_code,outs=AllIpGet(host,port,addr_pool_id,index) my_dict=dict() if(rtn_code!=-1): my_dict['response']=response_dic['success'] my_dict['candidate_ip']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') # return myresponse else: my_dict['error']=outs myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # 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 else: server_cmd=command_dic['vpncmd']+' '+server_ip+' '+command_dic['server'] # if(command=='ServerPasswordSet'): # server_pwd=request.GET.get('server_pwd',default='111111') # old_server_pwd=request.GET.get('old_server_pwd',default=None) # if(old_server_pwd==None): # command=server_cmd+command+' '+server_pwd # else: # command=server_cmd+command+' '+command_dic['password']+old_server_pwd+' '+command_dic['cmd']+' '+command+' '+server_pwd # elif(command='BridgeCreate'): # server_pwd=request.GET.get('server_pwd',default='111111') # hub_name=request.GET.get('hub_name',default='NewHub0') # device=request.GET.get('device',default=None) # tap=request.GET.get('tap',default=None) # command=server_cmd+' '+command_dic['password']+server_pwd+' '+command_dic['cmd']+' '+command+' '+hub_name+' '+command_dic['device']+device # +' '+command_dic['tap']+tap # elif(command=='AddIpTap'): # ip=request.GET.get('ip',default=None) # dev=request.GET.get('dev',default=None) # command='ip addr add'+' '+ip+' '+'dev'+' '+'tap_'+dev # elif(command=='IPsecEnable'): # l2tp=request.GET.get('l2tp',default=None) # l2tpraw=request.GET.get('l2tpraw',default=None) # etherip=request.GET.get('etherip',default=None) # psk=request.GET.get('psk',default=None) # defaulthub=request.GET.get('defaulthub',defaul=None) # command=server_cmd+' '+command_dic['password']+password+' '+command_dic['cmd']+' '+command+' '+command_dic['l2tp']+l2tp+\ # ' '+command_dic['l2tpraw']+l2tpraw+' '+command_dic['etherip']+etherip+' '+command_dic['psk']+psk+' '+command_dic['defaulthub']+\ # +defaulthub # elif(command=='SessionList'): # adminhub=request.GET.get('adminhub',default=None) # command=server_cmd+' '+command_dic['password']+password+' '+command_dic['adminhub']+' '+command_dic['password']+password+' '+\ # command_dic['csv']+' '+command_dic['cmd']+' '+command server_pwd=request.GET.get('server_pwd',default=server_pwd) hub_name=request.GET.get('hub_name',default=hub_name) hub_pwd=request.GET.get('hub_pwd',default='111111') hub_cmd=server_cmd+' '+command_dic['password']+server_pwd+' '+command_dic['hub']+hub_name+' '+command_dic['password']+hub_pwd+' '\ +command_dic['cmd'] hub_csv_cmd=server_cmd+' '+command_dic['password']+server_pwd+' '+command_dic['hub']+hub_name+' '+command_dic['password']+hub_pwd+' '\ +command_dic['csv']+' '+command_dic['cmd'] # if(command=='HubCreate'): # command=command_dic['vpncmd']+' '+command_dic['server_ip']+' '+command_dic['server']+' '\ # +command_dic['password']+command_dic['server_pwd']+' '+command['cmd']+' '+cmd+' '+hub_name+' '+password+hub_pwd # elif(command=='SecureNatEnable'): # command=hub_cmd+command # elif(command=='RadiusServerSet'): # radius_ip=request.GET.get('radius_ip',default='192.168.11.137:1812') # secret=request.GET.get('secret',default='111111') # retry_interval=request.GET.get('retry_interval',default='500') # command=hub_cmd+' '+command+' '+radius_ip+' '+command_dic['secret']+secret+command_dic['retry_interval']+retry_interval if(command=='UserCreate'): user_name=request.GET.get('user_name',default=None) user_pwd=request.GET.get('user_pwd',default=None) group=request.GET.get('group',default='none') realname=request.GET.get('realname',default='none') note=request.GET.get('note',default='none') if(user_name==None or user_pwd==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # 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) if(rtn_code==0): command=hub_cmd+' '+'UserPasswordSet'+' '+user_name+' '+command_dic['password']+user_pwd 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: command=command=hub_cmd+' '+'UserDelete'+' '+user_name mysubprocess(command) my_dict=dict() my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # return myresponse else: my_dict=dict() my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # return myresponse # elif(command=='UserRadiusSet'): # user_name=request.GET.get('user_name',default='\'*\'') # alias=request.GET.get('alias',default='none') # command=hub_cmd+' '+command+' '+user_name+' '+user_name+' '+command_dic['alias']+alias elif(command=='UserPasswordSet'): user_name=request.GET.get('user_name',default=None) user_pwd=request.GET.get('user_pwd',default=None) if(user_name==None or user_pwd==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # return myresponse else: command=hub_cmd+' '+command+' '+user_name+' '+command_dic['password']+user_pwd 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']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # return myresponse elif(command=='UserList'): command=hub_csv_cmd+' '+command outs,rtn_code=mysubprocess(command) if(rtn_code==0): my_dict=dict() my_dict['response']=response_dic['success'] my_list=outs.split('\n') user_dict=dict() user_list=list() for x in range(1,len(my_list)): user_info=my_list[x].split(',') if(len(user_info)<10): continue transfer_info=my_list[x].split('\"') user_dict['User_Name']=user_info[0] user_dict['Num_Logins']=user_info[5] if(user_info[6].find('None')==-1): # print(user_info[6]) temp_str=user_info[6].split(' ') temp_str=temp_str[0]+' '+temp_str[2] user_dict['Last_Login']=temp_str else: user_dict['Last_Login']='None' if(len(user_info)>10): user_dict['Transfer_Bytes']=transfer_info[1] user_dict['Transfer_Packets']=transfer_info[3] else: user_dict['Transfer_Bytes']=user_info[8] user_dict['Transfer_Packets']=user_info[9] user_list.append(user_dict) user_dict=dict() my_dict['userlist']=user_list myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json') # return myresponse else: my_dict=dict() my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # 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 else: command=hub_cmd+' '+command+' '+user_name # print(command) 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']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # return myresponse # elif(command=='IPTable'): # user_name=request.GET.get('user_name',default=None) # if(user_name==None): # myresponse=HttpResponse(json.dumps(response_dic['miss']),content_type='application/json',status=400) # return myresponse # else: # command=hub_cmd+' '+command+' '+user_name # if(hub_name==None): # command=server_cmd+' '+command_dic['password']+password+' '+command_dic['adminhub']+' '+command_dic['password']+password+' '+\ # command_dic['csv']+' '+command_dic['cmd']+' '+command elif(command=='UserGet'): 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 command=hub_csv_cmd+' '+command+' '+user_name outs,rtn_code=mysubprocess(command) if(rtn_code==0): my_dict=dict() my_dict['response']=response_dic['success'] my_list=outs.split('\n') for x in range(1,len(my_list)): user_info=my_list[x].split(',') transfer_info=re.split(r'(\"| )',my_list[x]) transfer_info_short=re.split(r'(,| )',my_list[x]) if(user_info[0]=='User Name'): my_dict['User_Name']=user_info[1] elif(user_info[0].find('Created on')!=-1): if(user_info[1].find('None')==-1): temp_str=user_info[1].split(' ') temp_str=temp_str[0]+' '+temp_str[2] my_dict['Create_on']=temp_str else: my_dict['Create_on']='None' elif(user_info[0].find('Update on')!=-1): my_dict['Update_on']=user_info[1] elif(user_info[0].find('Outgoing Unicast Packets')!=-1): if(my_list[x].find('\"')==-1): my_dict['Outgoing_Unicast_Packets']=transfer_info_short[6].replace(',','') else: my_dict['Outgoing_Unicast_Packets']=transfer_info[6].replace(',','') elif(user_info[0].find('Outgoing Unicast Total Size')!=-1): if(my_list[x].find('\"')==-1): my_dict['Outgoing_Unicast_Total_Size']=transfer_info_short[8].replace(',','') else: my_dict['Outgoing_Unicast_Total_Size']=transfer_info[8].replace(',','') elif(user_info[0].find('Outgoing Broadcast Packets')!=-1): # print(transfer_info,transfer_info_short) if(my_list[x].find('\"')==-1): my_dict['Outgoing_Broadcast_Packets']=transfer_info_short[6].replace(',','') else: my_dict['Outgoing_Broadcast_Packets']=transfer_info[6].replace(',','') elif(user_info[0].find('Outgoing Broadcast Total Size')!=-1): if(my_list[x].find('\"')==-1): my_dict['Outgoing_Broadcast_Total_Size']=transfer_info_short[8].replace(',','') else: my_dict['Outgoing_Broadcast_Total_Size']=transfer_info[8].replace(',','') elif(user_info[0].find('Incoming Unicast Packets')!=-1): if(my_list[x].find('\"')==-1): my_dict['Incoming_Unicast_Packets']=transfer_info_short[6].replace(',','') else: my_dict['Incoming_Unicast_Packets']=transfer_info[6].replace(',','') elif(user_info[0].find('Incoming Unicast Total Size')!=-1): if(my_list[x].find('\"')==-1): my_dict['Incoming_Unicast_Total_Size']=transfer_info_short[8].replace(',','') else: my_dict['Incoming_Unicast_Total_Size']=transfer_info[8].replace(',','') elif(user_info[0].find('Incoming Broadcast Packets')!=-1): if(my_list[x].find('\"')==-1): my_dict['Incoming_Broadcast_Packets']=transfer_info_short[6].replace(',','') else: my_dict['Incoming_Broadcast_Packets']=transfer_info[6].replace(',','') elif(user_info[0].find('Incoming Broadcast Total Size')!=-1): if(my_list[x].find('\"')==-1): my_dict['Incoming_Broadcast_Total_Size']=transfer_info_short[8].replace(',','') else: my_dict['Incoming_Broadcast_Total_Size']=transfer_info[8].replace(',','') elif(user_info[0].find('Number of Logins')!=-1): if(my_list[x].find('\"')==-1): my_dict['Number_of_Logins']=transfer_info_short[6].replace(',','') else: my_dict['Number_of_Logins']=transfer_info[6].replace(',','') if(my_dict.get('Create_on')==None): my_dict['Create_on']='' elif(my_dict.get('Update on')==None): my_dict['Update_on']='' elif(my_dict.get('Outgoing_Unicast_Packets')==None): my_dict['Outgoing_Unicast_Packets']='' elif(my_dict.get('Outgoing_Unicast_Total_Size')==None): my_dict['Outgoing_Unicast_Total_Size']='' elif(my_dict.get('Outgoing_Broadcast_Packets')==None): my_dict['Outgoing_Broadcast_Packets']='' elif(my_dict.get('Outgoing_Broadcast_Total_Size')==None): my_dict['Outgoing_Broadcast_Total_Size']='' elif(my_dict.get('Incoming_Unicast_Packets')==None): my_dict['Incoming_Unicast_Packets']='' elif(my_dict.get('Incoming_Unicast_Total_Size')==None): my_dict['Incoming_Unicast_Total_Size']='' elif(my_dict.get('Incoming_Broadcast_Packets')==None): my_dict['Incoming_Broadcast_Packets']='' elif(my_dict.get('Incoming_Broadcast_Total_Size')==None): my_dict['Incoming_Broadcast_Total_Size']='' 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 else: my_dict=dict() my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) # elif(command=='LogFileList'): # command=hub_cmd+' '+command # elif(command=='DownloadLogFile'): # file_addr=GET.get('user_name',default='./security_log/NewHub0/sec_20181031.log') # command=hub_cmd+' '+command+' '+file_addr elif(command=='UserPolicySet'): user_name=request.GET.get('user_name',default=None) policy_name=request.GET.get('name',default=None) value=request.GET.get('value',default=None) if(user_name==None or policy_name==None or value==None): my_dict=dict() my_dict['error']=response_dic['miss'] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) 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') else: my_dict=dict() my_dict['error']=Error_code[rtn_code] myresponse=HttpResponse(json.dumps(my_dict),content_type='application/json',status=400) 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') # command=hub_cmd+' '+command+' '+opt_set+command_dict['value']+value # elif(command=='DhcpSet'): # start_ip=request.GET.get('start_ip',default=None) # end=request.GET.get('end',default=None) # mask=request.GET.get('mask',default=None) # expire=request.GET.get('expire',default=None) # gw=request.GET.get('gw',default=None) # dns=request.GET.get('dns',default=None) # dns2=request.GET.get('dns2',default=None) # domain=request.GET.get('domain',default=None) # log=request.GET.get('log',default=None) # command==hub_cmd+' '+command+' '+command_dic['start']+start_ip+' '+command_dic['mask']+mask+' '+command_dic['expire']+expire\ # +' '+command_dic['gw']+gw+' '+command_dic['dns']+dns+' '+command_dic['dns2']+dns2+' '+command_dic['domain']+domain+' '+\ # command_dic['log']+log # elif(command=='SecureNatHostSet'): # mac=request.GET.get('mac',default=None) # ip=request.GET.get('ip',default=None) # mask=request.GET.get('mask',default=None) # command=hub_cmd+' '+command+' '+command_dic['mac']+mac+' '+command_dic['ip']+ip+' '+command_dic['mask']+mask # elif(command=='NatSet'): # mtu=request.GET.get('mtu',default=None) # tcptimeout=request.GET.get('tcptimeout',default=None) # udptimeout=request.GET.get('udptimeout',default=None) # log=request.GET.get('log',default=None) # command=hub_cmd+' '+command+' '+command_dic['mtu']+mtu+' '+command_dic['tcptimeout']+tcptimeout+' '+command_dic['udptimeout']+\ # udptimeout+' '+command_dic['log']+log # elif(command=='GroupCreate'): # group=request.GET.get('group',default='none') # realname=request.GET.get('realname',default='none') # note=request.GET.get('note',default='none') # command=hub_cmd+' '+command+' '+group+' '+command_dic['realname']+realname+' '+command_dic['note']+note # elif(command='UserPasswordSet'): # user_name=request.GET.get('user_name',default='\'*\'') # user_pwd=request.GET.get('user_pwd',default=None) # command=hub_cmd+' '+command+' '+user_name+' '+command_dic['password']+user_pwd # outs,rtn_code=mysubprocess(command) # if(rtn_code==0): # myresponse=HttpResponse(json.dumps(outs),content_type='application/json') # return myresponse # else: # myresponse=HttpResponse(json.dumps(response_dic['miss']),content_type='application/json',status=400) # return myresponse # elif cmd_obj=='client': # command=request.GET.get('cmd') # client_ip=request.GET.get('client_ip',default='localhost') # client_cmd=command_dic['vpncmd']+' '+command_dic['client']+client_ip+' '+command_dic['cmd'] # if(command=='NicCreate'): # nic_name=request.GET.get('nic_name',default='ethVPN3') # command=client_cmd+' '+command+' '+nic_name # elif(command=='AccountCreate'): # account_name=request.GET.get('account_name',default='AccountL3') # server_ip=request.GET.get('server_ip',default='192.168.11.137:443') # hub_name=request.GET.get('hub_name',default='HubRadiusTest') # user_name=request.GET.get('user_name',default='testing10') # nic_name=request.GET.get('nic_name',default='ethVPN3') # command=client_cmd+' '+command+' '+account+' '+command_dic['server']+':'+server_ip+' '+command_dic['hub']+hub_name+' '\ # +command_dic['username']+user_name+' '+command_dic['nic_name']+nic_name # elif(command=='AccountPassword'): # account=request.GET.get('account',default='AccountL3') # account_pwd=request.GET.get('account_pwd',default='111111') # account_type=request.GET.get('account_type',default='redius') # command=client_cmd+' '+command+' '+account+' '+command_dic['password']+account_pwd+command_dic['type']+account_type # elif(command=='AccountConnect'): # account=request.GET.get('account',default='AccountL3') # command=client_cmd+' '+command+' '+account # elif(command=='AccountStatusGet'): # account=request.GET.get('account',default='AccountL3') # command=client_cmd+' '+command+' '+account # elif(command=='dhclient'): # nic_name=request.GET.get('account',default='vpn_ethvpn3') # command='sudo'+' '+command+' '+nic_name def mysubprocess(command, timeout1 = 6): command = shlex.split(command) try: 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") outs = outs.decode("utf-8") rtn_code = ssh_process.returncode if rtn_code!= 0 and errs != '': # print("rtn_code: " + str(rtn_code)) # print("errs: " + errs) raise Exception("subprocess failed") return outs,rtn_code def readconfig(): myconfig=configparser.ConfigParser() myconfig.read("CGI_config.conf") server_pwd=myconfig.get("server","server_pwd") hub_name=myconfig.get("server","hub_name") host=myconfig.get("redis","host") port=myconfig.get("redis","port") index=myconfig.get("redis","index") return server_pwd,host,port,index,hub_name def IpExist(host,port,candidate_ip,index): P=Redis(host,port,index) rtn,outs=P.connect() my_set=set() if(rtn!=-1): scan_CANDIDATE=P.r.scan_iter(match="EFFECTIVE_RULE:IR_CANDIDATE_IP*") for i in scan_CANDIDATE: temp_list=P.r.get(i).split("\t") my_set.add(temp_list[3]) if candidate_ip in my_set: return 0,'true' else: return 0,'false' else: return -1,outs def IpNumGet(host,port,addr_pool_id,index):# IpNumGet(group_id) P=Redis(host,port,index) rtn,outs=P.connect() my_set=set() if(rtn!=-1): scan_CANDIDATE=P.r.scan_iter(match="EFFECTIVE_RULE:IR_CANDIDATE_IP*") for i in scan_CANDIDATE: temp_list=P.r.get(i).split("\t") if(temp_list[1]==addr_pool_id): my_set.add(temp_list[3]) return len(my_set),outs else: return -1,outs def AllIpGet(host,port,addr_pool_id,index):# AllIpGet(group_id) P=Redis(host,port,index) rtn,outs=P.connect() my_set=set() if(rtn!=-1): scan_CANDIDATE=P.r.scan_iter(match="EFFECTIVE_RULE:IR_CANDIDATE_IP*") for i in scan_CANDIDATE: temp_list=P.r.get(i).split("\t") if(temp_list[1]==addr_pool_id): my_set.add(temp_list[3]) return 0,list(my_set) else: return -1,outs