def checkPackageIP(self, ip, action): j = ip.split(',') k = 'PackageID' if action == 'AddProtectPackageIP': return True if 'IP' in self.params and k in self.params: user_org = self.get_argument('AccessKeyId') if 'IPUserID' in self.params: user_end = self.get_argument('IPUserID') else: res = sc(code.ParamError) res.result = res.result % '请输入IPUserID' return res v = self.get_argument(k) desc_sql = 'b.status=True' if 'DescribeIP' not in action else '1=1' for i in j: sql = 'select 1 from t_package_protect a join t_ip_protect b on a.id=b.package where a.package_protect_id=%s and b.user_org=%s and b.user_end=%s and b.ip=%s and {0};'.format( desc_sql) data = self.application.dbcur.queryall_dict( sql, (v, user_org, user_end, i)) if data: return True else: res = sc(code.PermissionDenied) res.result = res.result % ip return res
def run(self): ip = self.params['IP'] data_info = dict() data_info['DescribeIPFirewallProtectData'] = dict() firewall = Firewall(self.application.ccfirewall) protect_dict = firewall.query_protect_serial_number(ip) try: param_set = self.application.param_set_dict[ protect_dict['param_set']] port_tcp = self.application.port_tcp_dict[protect_dict['PortTCP']] except KeyError: res = sc(code.IPNotExist) res.result = res.result % ip raise gen.Return(res) # if param_set == '0': # result = 'loose' # elif param_set == '1': # result = 'medium' # elif param_set == '2': # result = 'tight' if int(param_set) > 2: param_set = 'Not in correct global protect level' if int(port_tcp) > 2: port_tcp = 'Not in correct web protect level' data_info['DescribeIPFirewallProtectData'][ 'GlobalProtectLevel'] = param_set data_info['DescribeIPFirewallProtectData'][ 'WebProtectLevel'] = port_tcp res = sc(code.Success) res.redata = data_info raise gen.Return(res)
def init_remote(self): self.shell = paramiko.SSHClient() self.shell.set_missing_host_key_policy(paramiko.AutoAddPolicy()) PRIVATE_KEY = paramiko.RSAKey.from_private_key_file(self.private_key) try: self.shell.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password, pkey=PRIVATE_KEY, timeout=self.timeout) self.sftpcon = paramiko.Transport((self.hostname, self.port)) self.sftpcon.connect(username=self.username, password=self.password, pkey=PRIVATE_KEY) self.file = paramiko.SFTPClient.from_transport(self.sftpcon) except Exception as e: if type(e).__name__ == 'timeout': res = sc(code.RemoteSerConnTimeout) res.result = res.result % self.hostname return res if type(e).__name__ == 'AuthenticationException': res = sc(code.RemoteSerAuthFaile) res.result = res.result % self.hostname return res res = sc(code.RemoteSerConnFaile) res.result = res.result % self.hostname return res return True
def run(self): operator = self.params['Operator'] hostname = self.params['Hostname'] data_info = {} if not netutil.is_valid_ip(hostname): res = sc(code.ParamError) res.result = res.result % hostname raise gen.Return(res) thread_list = [] data_status = {} fw_list = self.application.firewalllist if operator == 'bgp' else [ self.application.ccfirewall, operator ] for i in fw_list: t = MyThread(self.select_ip, args=(i, hostname)) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() for index, item in enumerate(thread_list): data_status[fw_list[index]] = item.get_result() print(data_status) for k, v in data_status.items(): if '白' not in v: data_info['DescribeIPFirewallList'] = operator + ':IP不在白名单' break else: data_info['DescribeIPFirewallList'] = operator + ':IP在白名单' res = sc(code.Success) res.redata = data_info raise gen.Return(res)
def run(self): source_ip = self.params['SourceIP'] operator = self.params['Operator'] if not netutil.is_valid_ip(source_ip): res = sc(code.ParamError) raise gen.Return(res) data_info = {} data_info['BlockListData'] = [] data_status = {} thread_list = [] fw_list = self.application.firewalllist if operator == 'bgp' else [ self.application.ccfirewall, operator ] for i in fw_list: t = MyThread(self.select_block, args=(i, source_ip)) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() for index, item in enumerate(thread_list): data_status[fw_list[index]] = item.get_result() for k, v in data_status.items(): data_info['BlockListData'].append({k: v}) res = sc(code.Success) res.redata = data_info raise gen.Return(res)
def run(self): res = sc(code.Success) res.result = 'Success' action = self.params['Action'] packageid = self.params['PackageID'] ips = self.params['IP'] ip_l = self.params['IP'].split(',') user_org = self.params['AccessKeyId'] user_end = self.params['IPUserID'] uuids_list, uuids_str, ips_list, ips_str = get_ip_serialuuids( user_org=user_org, user_end=user_end, ips=ips, status='open') if len(ip_l) != len(ips_list): ip_r = list(set(ip_l).difference(set(ips_list))) res = sc(code.IPNotUsed) res.result = res.result % str(','.join(ip_r)) raise gen.Return(res) ts = self.application.ts_begin for ip in ip_l: del_fw_dict = self.delete_firewall_configs(ip) if len(del_fw_dict) != 0: res = sc(code.CommitFail) res.result = res.result % str(del_fw_dict) raise gen.Return(res) white_info = dict() white_info['serialnum'] = packageid white_info['ts'] = white_info['ts_actions'] = ts white_info['p5'] = ip white_info['actions'] = 'DeleteWhiteList' sql = "select hostname,status from t_firewall where ip=%s and status>0" w_data = self.application.dbcur.queryall_dict(sql, (ip, )) if w_data: for w in w_data: white_info['p1'] = w['hostname'] white_info['p2'] = w['status'] self.application.dbcur.insert_dict('t_job', white_info) proxy_sql = "UPDATE t_slb_four_layer SET configtype = 'Del' WHERE ip=%s;UPDATE t_slb_seven_layer SET configtype = 'Del' WHERE ip=%s" self.application.dbcur.execute(proxy_sql, ( ip, ip, )) self.application.dbcurflow.execute( 'delete from t_ip_credit where ip=%s;', (ip, )) for uuid in uuids_list: ts = self.application.ts_begin sql = 'update t_ip_protect set (ts_shut,status)=(%s,False) where serialnum=%s and status=TRUE;' self.application.dbcur.execute(sql, ( ts, uuid, )) self.application.history_backup_t_ip_protect( column_extra_value=",'{cts}','{action}'".format(cts=ts, action=action), filter="serialnum='{serialnum}'".format(serialnum=uuid)) raise gen.Return(res)
def del_ip(self, operator, hostname, data_add, user_dict): firewall = ZhiFirewall(operator) if operator in self.application.zhifirewalllist else Firewall(operator) if str(user_dict)[:-1] in str(data_add[0]): if firewall.del_white_list(hostname): return hostname + ':IP从白名单删除' else: return sc(code.FirewallConnFail).result % hostname else: return sc(code.IPError).result % hostname
def run(self): ts = self.application.ts_begin ip = self.params['IP'] serialuuid = self.params['UUID'] user_org = self.params['AccessKeyId'] user_end = self.params[ 'IPUserID'] if 'IPUserID' in self.params else None if len(ip.split(',')) > 1: res = sc(code.ParamError) raise gen.Return(res) sql = "SELECT cfgfile FROM t_slb_seven_layer WHERE ip=%s AND uuid=%s and configtype !='Del'" data = self.application.dbcur.queryone(sql, ( ip, serialuuid, )) if not data: res = sc(code.SLBConfNotExist) res.result = res.result % serialuuid raise gen.Return(res) old_cfgfile = data[0] data = self.application.dbcur.queryall_dict( 'select name,value,type,idx from t_sys_parameter') sys_parameter = { ret['name'] + ret['idx']: { ret['idx']: ret['value'] } for ret in data } remoteser = RemoteOper(hostname=ip) res = remoteser.init_remote() if isinstance(res, sc): raise gen.Return(res) remoteser.file.remove(old_cfgfile) # restart|reload nginx stdin, stdout, stderr = remoteser.exec_cmd( sys_parameter['SLBNginxRESTART' + 'HTTP']['HTTP']) execret = stdout.readlines() + stderr.readlines() # with open('C:\Temp\seven.log', 'w') as seven: with open('/tmp/new_seven.log', 'w') as seven: seven.write(str(ts) + '\r\n') seven.write(str(stdin) + '\r\n') seven.write(str(execret) + '\r\n') remoteser.put_file(seven.name, '/logs/nginx/new_seven.log') remoteser.exec_cmd( 'cat /logs/nginx/new_seven.log >> /logs/nginx/seven.log') os.remove(seven.name) if os.path.isfile(seven.name) else None self.application.dbcur.execute( "UPDATE t_slb_seven_layer SET configtype='Del' where ip=%s and uuid=%s", ( ip, serialuuid, )) res = sc(code.Success) res.result = 'Success' raise gen.Return(res)
def del_domain(self, operator, hostname, data_add, user_dict): firewall = ZhiFirewall(operator) if operator in self.application.zhifirewalllist else Firewall(operator) if str(user_dict)[:-1] in str(data_add[0]): # 本人加的 if firewall.del_domain_name(hostname): return hostname + ':域名从白名单删除' else: return sc(code.FirewallConnFail).result % hostname else: return sc(code.DomainError).result % hostname
def run(self): res = sc(code.Success) res.result = 'Success' action = self.params['Action'] ts = self.application.ts_begin ip = self.params['IP'] ip_s = self.params['IP'] ip_l = self.params['IP'].split(',') user_org = self.params['AccessKeyId'] user_end = self.params['IPUserID'] if 'IPUserID' in self.params else None uuids_list, uuids_str, ips_list, ips_str = get_ip_serialuuids(user_org=user_org, user_end=user_end, ips=ip, status='open') if len(ip_l) != len(ips_list): ip_r = list(set(ip_l).difference(set(ips_list))) res = sc(code.IPNotUsed) res.result = res.result % str(','.join(ip_r)) raise gen.Return(res) sql = 'SELECT host(ip) AS ip FROM t_ip_protect WHERE serialnum IN (%s) AND protect_state=0' data = self.application.dbcur.queryall_dict(sql, (uuids_str.replace('"', ""),)) if data: ip_r = [x['ip'] for x in data] if ip_r: res = sc(code.NotInCorrectStatus) res.result = res.result % ip raise gen.Return(res) if uuids_str: sql = "SELECT protect_state FROM t_ip_protect WHERE serialnum in (%s)" data = self.application.dbcur.queryall_dict(sql, (uuids_str.replace('"', ''),)) if data: ip_info = {} ip_info['protect_state'] = 0 # sql_1 = "SELECT protect_base, protect_max FROM t_ip_protect WHERE serialnum in (%s)" # data = self.application.dbcur.queryall_dict(sql_1, (uuids_str.replace('"', ''),))[0] # ip_info['protect_previous'] = json.dumps(data) # sql_2 = "SELECT bandtype_id FROM t_ip_protect INNER JOIN t_bandtype ON t_bandtype.id = t_ip_protect.bandtype WHERE serialnum in (%s)" # bandtype = self.application.dbcur.queryall(sql_2, (uuids_str.replace('"', ''),))[0] # band_free = bandtype[0].lower()+'free' # sql_3 = "SELECT id FROM t_protect WHERE protect_id=%s" # ip_info['protect_base'] = ip_info['protect_max'] = self.application.dbcur.queryall(sql_3, (band_free,))[0][0] self.application.dbcur.update_dict('t_ip_protect', ip_info, 'serialnum', uuids_str.replace('"', '')) # sql = 'INSERT INTO t_ip_protect_his (ip,user_org,user_end,protect_base,protect_max,protect_previous,ts_open,ts_shut,metric_pct_pps,metric_pct_bps,region,zone,serialnum,status,cts,actions,protect_state,iptype,bandtype) SELECT ip,user_org,user_end,protect_base,protect_max,protect_previous,ts_open,ts_shut,metric_pct_pps,metric_pct_bps,region,zone,serialnum,status,%s,%s,protect_state,iptype,bandtype FROM t_ip_protect WHERE serialnum = %s' # self.application.dbcur.execute(sql, (ts, action, uuids_str.replace('"', ""),)) self.application.history_backup_t_ip_protect(column_extra_value=",'{cts}','{action}'".format(cts=ts, action=action), filter="serialnum='{serialnum}'".format(serialnum=uuids_str.replace('"', ""))) else: res = sc(code.IPNotUsed) res.result = res.result % ip_s raise gen.Return(res)
def run(self): res = sc(code.Success) res.result = 'Success' actions = self.params['Action'] packageid = self.params['PackageID'] user_org = self.params['AccessKeyId'] user_end = self.params[ 'IPUserID'] if 'IPUserID' in self.params else None sql = 'select id from t_package_protect where package_protect_id=%s and user_org=%s and user_end=%s and status=True;' self.application.dbcur.execute(sql, (packageid, user_org, user_end)) package = self.application.dbcur.fetchall() if not package: res = sc(code.PackageStatusError) res.result = res.result % '请检查服务包状态' raise gen.Return(res) sql = 'select host(ip) as ip from t_ip_protect where package=%s and status=True;' self.application.dbcur.execute(sql, (package[0][0], )) data = self.application.dbcur.fetchall() if data: res = sc(code.PackageIPError) res.result = res.result % data raise gen.Return(res) ts = self.application.ts_begin white_info = dict() white_info['serialnum'] = packageid white_info['ts'] = white_info['ts_actions'] = ts white_info['p5'] = packageid white_info['actions'] = 'DeleteWhiteList' sql = "select hostname,status from t_firewall where package_protect_id=%s and status>0" w_data = self.application.dbcur.queryall_dict(sql, (packageid, )) if w_data: for w in w_data: white_info['p1'] = w['hostname'] white_info['p2'] = w['status'] self.application.dbcur.insert_dict('t_job', white_info) sql = 'update t_package_protect set (ts_shut,status)=(%s,False) where package_protect_id=%s and status=TRUE;' self.application.dbcur.execute(sql, ( ts, packageid, )) self.application.history_backup_t_package_protect( column_extra_value=",'{cts}','{action}'".format(cts=ts, action=actions), filter="package_protect_id='{packageid}'".format( packageid=packageid)) sql = "delete from t_job where serialnum=%s AND actions<>'DeleteWhiteList'" self.application.dbcur.execute(sql, (packageid, )) raise gen.Return(res)
def run(self): res = sc(code.Success) res.result = 'Success' action = self.params['Action'] packageid = self.params['PackageID'] user_org = self.params['AccessKeyId'] user_end = self.params['IPUserID'] sql = 'select id from t_package_protect where package_protect_id=%s and user_org=%s and user_end=%s and status=True;' self.application.dbcur.execute(sql, (packageid, user_org, user_end)) package = self.application.dbcur.fetchall() if not package: res = sc(code.PackageNotExist) res.result = res.result % '请检查PackageID或IPUserID' raise gen.Return(res) sql = "select package_protect_id from t_package_protect where package_protect_id=%s and protect_state in (0,1)" data = self.application.dbcur.queryall_dict(sql, (packageid, )) if data: res = sc(code.NotInCorrectStatus) res.result = res.result % packageid raise gen.Return(res) ts = self.application.ts_begin sql1 = 'update t_package_protect set protect_state=1 where package_protect_id=%s and status=TRUE;' self.application.dbcur.execute(sql1, (packageid, )) sql = 'update t_ip_protect set protect_state=1 where package=%s and status=TRUE;' self.application.dbcur.execute(sql, (package[0][0], )) # sql = 'INSERT INTO t_ip_protect_his (ip,package,user_org,user_end,protect_base,protect_max,protect_previous,' \ # 'ts_open,ts_shut,metric_pct_pps,metric_pct_bps,region,zone,serialnum,status,cts,actions,protect_state,' \ # 'iptype,bandtype) ' \ # 'SELECT ip,package,user_org,user_end,protect_base,protect_max,protect_previous,ts_open,ts_shut,' \ # 'metric_pct_pps,metric_pct_bps,region,zone,serialnum,status,%s,%s,protect_state,iptype,bandtype ' \ # 'FROM t_ip_protect WHERE package =%s;' # self.application.dbcur.execute(sql, (ts, action, package[0][0], )) self.application.history_backup_t_ip_protect( column_extra_value=",'{cts}','{action}'".format(cts=ts, action=action), filter="package='{package}'".format(package=package[0][0])) # sql = 'INSERT INTO t_package_protect_his ' \ # '(package,ipnums,package_protect_id,package_protect_name,user_org,user_end,protect_state,ts_open,' \ # 'ts_shut,serialnum,status,cts,actions) SELECT package,ipnums,package_protect_id,package_protect_name,' \ # 'user_org,user_end,protect_state,ts_open,ts_shut,serialnum,status,%s,%s' \ # 'FROM t_package_protect WHERE package =%s;' # self.application.dbcur.execute(sql, (ts, action, package[0][0],)) self.application.history_backup_t_package_protect( column_extra_value=",'{cts}','{action}'".format(cts=ts, action=action), filter="package_protect_id='{packageid}'".format( packageid=packageid)) raise gen.Return(res)
def run(self): res = sc(code.Success) res.result = 'Success' action = self.params['Action'] ts = self.application.ts_begin ip = self.params['IP'] serialuuid = self.params['UUID'] accesskeyid = self.params['AccessKeyId'] if len(ip.split(',')) > 1: res = sc(code.ParamError) raise gen.Return(res) try: ipaddress.ip_address(ip) except: res = sc(code.ParamError) raise gen.Return(res) sql = "SELECT cfgfile from t_slb_four_layer where ip=%s and uuid=%s and configtype !='Del'" data = self.application.dbcur.queryone(sql, (ip, serialuuid,)) if not data: res = sc(code.SLBConfNotExist) res.result = res.result % serialuuid raise gen.Return(res) old_cfgfile = data[0] data = self.application.dbcur.queryall_dict('select name,value,type,idx from t_sys_parameter') sys_parameter = {ret['name'] + ret['idx']: {ret['idx']: ret['value']} for ret in data} remoteser = RemoteOper(hostname=ip) res = remoteser.init_remote() if isinstance(res, sc): raise gen.Return(res) remoteser.file.remove(old_cfgfile) # restart|reload nginx stdin, stdout, stderr = remoteser.exec_cmd(sys_parameter['SLBNginxRESTART' + 'TCP']['TCP']) execret = stdout.readlines() + stderr.readlines() # with open('C:\Temp/new_four.log', 'w') as four: with open('/tmp/new_four.log', 'w') as four: four.write(str(ts) + '\r\n') four.write(str(stdin) + '\r\n') four.write(str(execret) + '\r\n') remoteser.put_file(four.name, '/logs/nginx/new_four.log') remoteser.exec_cmd('cat /logs/nginx/new_four.log >> /logs/nginx/four.log') os.remove(four.name) if os.path.isfile(four.name) else None # if execret: # res = sc(code.RemoteSerExecCMDErr) # res.result = res.result % (str(execret) + ip) # return res sql = "UPDATE t_slb_four_layer SET configtype='Del' where ip=%s and uuid=%s" self.application.dbcur.execute(sql, (ip, serialuuid,)) res = sc(code.Success) res.result = 'Success' raise gen.Return(res)
def run(self): action = self.params['Action'] ts = self.application.ts_begin ip = self.params['IP'] ip_l = self.params['IP'].split(',') user_org = self.params['AccessKeyId'] user_end = self.params[ 'IPUserID'] if 'IPUserID' in self.params else None uuids_list, uuids_str, ips_list, ips_str = get_ip_serialuuids( user_org=user_org, user_end=user_end, ips=ip, status='open') if len(ip_l) != len(ips_list): ip_r = list(set(ip_l).difference(set(ips_list))) res = sc(code.IPNotUsed) res.result = res.result % str(','.join(ip_r)) raise gen.Return(res) sql = "select host(ip) ip from t_ip_protect where serialnum in (%s) and protect_state in (0,1)" data = self.application.dbcur.queryall_dict( sql, (uuids_str.replace('"', ''), )) if data: ip_r = [x['ip'] for x in data] if ip_r: res = sc(code.NotInCorrectStatus) res.result = res.result % ip raise gen.Return(res) if uuids_str: sql = "SELECT protect_state FROM t_ip_protect WHERE serialnum in (%s)" data = self.application.dbcur.queryall_dict( sql, (uuids_str.replace('"', ''), )) if data: ip_info = {} ip_info['protect_state'] = 1 self.application.dbcur.update_dict('t_ip_protect', ip_info, 'serialnum', uuids_str.replace('"', '')) # sql = "insert into (serialnum, ip, user_org, user_end, protect_base, protect_max, protect_state, protect_previous, ts_open, ts_shut, metric_pct_bps, metric_pct_pps, region, zone, status, cts, actions,iptype,bandtype) SELECT serialnum, ip, user_org, user_end, protect_base, protect_max, protect_state, protect_previous, ts_open, ts_shut, metric_pct_bps, metric_pct_pps, region, zone, status, %s, %s,iptype,bandtype FROM t_ip_protect WHERE serialnum IN (%s)" # self.application.dbcur.execute(sql, (str(ts).replace('"', ''), action, uuids_str.replace('"', ''),)) self.application.history_backup_t_ip_protect( column_extra_value=",'{cts}','{action}'".format(cts=ts, action=action), filter="serialnum='{serialnum}'".format( serialnum=uuids_str.replace('"', ""))) res = sc(code.Success) res.result = 'Success' else: res = sc(code.DataNotConform) res.result = res.result % ip raise gen.Return(res)
def checkPermission(self): AccessKeySecret = self.getKey(self.params["AccessKeyId"]) if not AccessKeySecret: res = sc(code.ParamError) res.result = res.result % "AccessKeyId" return res hmacStr = hmac.new(AccessKeySecret.encode(), self.dealparam(self.params).encode(), hashlib.sha1) sign = base64.b64encode(hmacStr.digest()) if self.params["Signature"] != sign.decode('utf-8'): res = sc(code.ParamError) res.result = res.result % "Signature" return res return True
def checkProtectGroup(self): k = 'BandwithType' if k in self.params: v = self.get_argument(k) sql = 'select id from t_bandtype where bandtype_id=%s;' data = self.application.dbcur.queryall_dict(sql, (v, )) bandtype = data[0]['id'] if data else None else: bandtype = None k_list = [ 'guaranteeProtectGroupID', 'elasticProtectGroupID', 'GuaranteeProtectGroupID', 'ElasticProtectGroupID' ] for k in k_list: if k in self.params: v = self.get_argument(k) if bandtype: sql = 'select 1 from t_protect where protect_id=%s and bandtype=%s;' data = self.application.dbcur.queryall_dict( sql, (v, bandtype)) else: sql = 'select 1 from t_protect where protect_id=%s;' data = self.application.dbcur.queryall_dict(sql, (v, )) if data: pass else: res = sc(code.ProtectGroupNotExit) res.result = res.result % v return res return True
def run(self): ips = self.params['IP'] if 'IP' in self.params else None user_org = self.params['AccessKeyId'] ip_l = ips.split(',') data_info = {} data_info['IPBlackHoleData'] = [] for ip in ip_l: sql = """ SELECT HOST (ip) AS ip, CASE WHEN line=0 THEN 'total' WHEN line=1 then 'ctc' when line=2 then 'cmcc' WHEN line=3 THEN 'cnc'END as line, to_char((ts - INTERVAL '8 hours'), 'YYYY-MM-DD-THH24:MI:SSZ') AS createdt, to_char((ts + b.ban_time- INTERVAL '8 hours'), 'YYYY-MM-DD-THH24:MI:SSZ') AS enddt, current_value, threshold_value, to_char(b.ban_time,'HH24:MI:SS') AS ban_time, direction FROM t_blockhole b WHERE ip = %s""" data = self.application.dbcurflow.queryall_dict(sql, (ip,)) count_data = {} count_data['IP'] = ip count_data['Line'] = data[0]['line'] if data else '' count_data['Createdt'] = data[0]['createdt'].replace('-T', 'T') if data else '' count_data['Enddt'] = data[0]['enddt'].replace('-T', 'T') if data else '' count_data['Current_value'] = data[0]['current_value'] if data else '' count_data['Threshold_value'] = data[0]['threshold_value'] if data else '' count_data['Ban_time'] = data[0]['ban_time'] if data else '' count_data['Direction'] = data[0]['direction'] if data else '' count_data['IPState'] = 'Normal' if not data else 'BlackHole' data_info['IPBlackHoleData'].append(count_data) res = sc(code.Success) res.result = 'Success' res.redata = data_info raise gen.Return(res)
def run(self): res = sc(code.Success) res.result = 'Success' user_org = self.params['AccessKeyId'] user_end = self.params[ 'IPUserID'] if 'IPUserID' in self.params else None user_end_sql = " a.user_end='" + user_end + "' " if user_end else " 1=1 " package_id = self.params[ 'PackageID'] if 'PackageID' in self.params else None package_id_sql = "a.package_protect_id='" + package_id + "'" if package_id else '1=1' sql = """select case when wm_concat(host(ip)) is not null then wm_concat(host(ip)) else ''end as "IPs", count(ip) as "IPNumsUsed",a.package_protect_name as "PackageName",a.package_protect_id as "PackageID", a.ipnums as "IPNums",replace(to_char(a.ts_due-INTERVAL '8 HOURS','YYYY-MM-DD HH24:MI:SSZ'),' ','T') as "DueTime", case when a.protect_state=2 then 'Elastic' when a.protect_state=1 then 'Guarantee' else 'Free' end as "ProtectStatus",c.protect_id as "GuaranteeProtect",d.protect_id as "ElasticProtect", case when a.status=True then 'open' else 'close' end as "Status", replace(to_char(a.ts_open-INTERVAL '8 HOURS','YYYY-MM-DD HH24:MI:SSZ'),' ','T') as "OpenTimeStamp", case when a.ts_shut is not null then replace(to_char(a.ts_shut-INTERVAL '8 HOURS','YYYY-MM-DD HH24:MI:SSZ'),' ','T') else '' END as "CloseTimeStamp" from t_package_protect a left JOIN t_ip_protect w on w.package=a.id and w.status=TRUE LEFT JOIN t_protect c on a.protect_base=c.id LEFT JOIN t_protect d on a.protect_max=d.id where a.user_org=%s and {0} and {1} GROUP BY w.package,a.package_protect_name,a.ipnums,a.protect_state,c.protect_id,a.status,a.ts_due, a.package_protect_id,d.protect_id,a.ts_open,a.ts_shut,w.package;""".format( package_id_sql, user_end_sql) data = self.application.dbcur.queryall_dict(sql, (user_org, )) data_info = dict() data_info['ProtectPackageInfo'] = data res.redata = data_info raise gen.Return(res)
def checkZone(self): pre_k = 'Region' k = 'Zone' if k in self.params and pre_k not in self.params: res = sc(code.ParamAbsence) res.result = res.result % pre_k return res if k in self.params: pre_v = self.get_argument(pre_k) v = self.get_argument(k) sql = 'select 1 from t_zone a, t_region b where a.region=b.id and b.region_id=%s and a.zone_id=%s;' data = self.application.dbcur.queryall_dict(sql, (pre_v, v)) if data: return True else: res = sc(code.ZoneNotExist) res.result = res.result % v return res
def run(self): source_ip = self.params['SourceIP'] remote_ip = self.params['RemoteIP'] operator = self.params['Operator'] user_org = self.params['AccessKeyId'] user_end = self.params[ 'IPUserID'] if 'IPUserID' in self.params else None ts = self.application.ts_begin if not (netutil.is_valid_ip(source_ip) and netutil.is_valid_ip(remote_ip)): res = sc(code.ParamError) raise gen.Return(res) data_info = {} data_info['ResetBlockIPData'] = [] data_status = {} thread_list = [] condition = 0 fw_list = self.application.firewalllist if operator == 'bgp' else [ self.application.ccfirewall, operator ] for i in fw_list: t = MyThread(self.reset_block, args=(i, source_ip)) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() for index, item in enumerate(thread_list): data_status[fw_list[index]] = item.get_result() for k, v in data_status.items(): if v != 200: condition = '' if isinstance(condition, int): data_info['ResetBlockIPData'] = operator + ':屏蔽列表已重置' res = sc(code.Success) res.redata = data_info else: res = sc(code.ChangeFail) res.result = res.result % {operator + ':屏蔽列表重置失败'} raise gen.Return(res)
def remove_file(self, remote): try: self.file.remove(remote) except Exception as e: if type(e).__name__ == 'IOError': res = sc(code.RemoteSerIOErr) res.result = res.result % (str(e) + ':[' + remote + '] ' + self.hostname) return res return True
def add_ip(self, operator, hostname, data_add, user_dict): firewall = ZhiFirewall(operator) if operator in self.application.zhifirewalllist else Firewall(operator) if firewall.select_white_list(hostname) == 'black': return hostname + ':IP已在黑名单,请联系运维人员' if data_add: if str(user_dict)[:-1] in str(data_add[0]): # 本人加的 if firewall.add_white_list(hostname): return hostname + ':IP添加至白名单' else: return sc(code.FirewallConnFail).result % hostname else: return sc(code.IPError).result % hostname else: # 没有人有加 if firewall.add_white_list(hostname): return hostname + ':IP添加至白名单' else: return sc(code.FirewallConnFail).result % hostname
def checkRegion(self): k = 'Region' if k in self.params: v = self.get_argument(k) sql = 'select 1 from t_region where region_id=%s;' data = self.application.dbcur.queryall_dict(sql, (v, )) if data: return True else: res = sc(code.RegionNotExist) res.result = res.result % v return res
def checkBandwithType(self): k = 'BandwithType' if k in self.params: v = self.get_argument(k) sql = 'select 1 from t_bandtype where bandtype_id=%s;' data = self.application.dbcur.queryall_dict(sql, (v, )) if data: return True else: res = sc(code.BandwithTypeNotExist) res.result = res.result % v return res
def checkIPOwner(self, ip_list, action, myAccessKey): action_disable = [ 'ModifyIPProtectGroup', 'CloseIPElasticAntiDDos', 'OpenIPElasticAntiDDos', 'CloseIPAntiDDos', 'OpenIPAntiDDos', 'DeleteProtectGroupIP' ] if 'DescribeNormalIP' in action or action == 'AddProtectGroupIP': return True if action in action_disable: for ip in ip_list.split(','): sql = 'select count(1) is_exists,user_org from t_ip_protect where ip=%s and status =TRUE group by user_org' data = self.application.dbcur.queryall_dict(sql, (ip, )) if not data: res = sc(code.IPNotExist) res.result = res.result % ip return res sql = 'select count(1) is_exists,user_org from t_ip_protect where ip=%s and status=TRUE AND package is null group by user_org' data = self.application.dbcur.queryall_dict(sql, (ip, )) if not data: res = sc(code.PermissionDenied) res.result = res.result % '不允许对服务包IP进行此操作' return res user_org = [x['user_org'] for x in data] if myAccessKey not in user_org: res = sc(code.PermissionDenied) res.result = res.result % ip return res if 'DescribeIP' in action and action != 'DescribeIPInfo': for ip in ip_list.split(','): sql = 'select count(1) is_exists,user_org from t_ip_protect where ip=%s group by user_org' data = self.application.dbcur.queryall_dict(sql, (ip, )) if not data: res = sc(code.IPNotExist) res.result = res.result % ip return res user_org = [x['user_org'] for x in data] if myAccessKey not in user_org: res = sc(code.PermissionDenied) res.result = res.result % ip return res else: for ip in ip_list.split(','): sql = 'select count(1) is_exists,user_org from t_ip_protect where ip=%s AND status=TRUE group by user_org' data = self.application.dbcur.queryall_dict(sql, (ip, )) if not data: res = sc(code.IPNotUsed) res.result = res.result % ip return res user_org = [x['user_org'] for x in data] if myAccessKey not in user_org: res = sc(code.PermissionDenied) res.result = res.result % ip return res return True
def run(self): res = sc(code.Success) res.result = 'Success' sql = """select a.package_id as "PackageID",a.package_name as "Packagename",a.ipnums as "IPNums", b.protect_name as "BaseProtectName",b.max_bps_in/1000/1000/1000 as "BaseProtectValue", c.protect_name as "MaxProtectName",c.max_bps_in/1000/1000/1000 as "MaxProtectValue" from t_package a,t_protect b,t_protect c where a.protect_base=b.id and a.protect_max=c.id and a.status=True;""" data = self.application.dbcur.queryall_dict(sql) data_info = {} data_info['SysPackageInfo'] = data res.redata = data_info raise gen.Return(res)
def checkParamType(self, Action, Param): pk = "_".join([Action, Param]) cre = '' clist = [] if pk in bgpParams.ParamTrans: cre = bgpParams.ParamTrans[pk][2] elif Param in bgpParams.ParamTrans: cre = bgpParams.ParamTrans[Param][2] if cre != "" and cre.find("@") != -1: clist = cre.split("@") isRaise = False if clist[0] == "TIME": try: time.strptime(self.params[Param], clist[1]) except: isRaise = True elif clist[0] == "RE": m = re.match(clist[1], self.params[Param]) if not m: isRaise = True elif clist[0] == 'IP': iplist = self.params[Param].split(',') for ip in iplist: try: ipaddress.ip_address(ip) except: isRaise = True elif clist[0] == "TYPE": try: inmsg = self.params[Param] inmsg = inmsg.replace('null', 'None') inmsg = inmsg.replace('true', 'True') inmsg = inmsg.replace('false', 'False') inmsg = eval(inmsg) if clist[1] == "list": if not isinstance(inmsg, list): isRaise = True elif clist[1] == "dict": if not isinstance(inmsg, dict): isRaise = True except: isRaise = True if isRaise: res = sc(code.ParamError) # res.result = res.result % Param res.result = res.result % '[' + Param + ':' + self.params[ Param] + ']' return res return True
def checkActionParams(self, Action, Param): isneed = True if Param[0:1] == '_': isneed = False Param = Param[1:] if isneed and Param not in self.params: res = sc(code.ParamAbsence) res.result = res.result % Param return res if Param in self.params: res = self.checkParamType(Action, Param) if isinstance(res, sc): return res return True
def checkParams(self): for p in bgpParams.CommonParams: # if not self.params.has_key(p): if p not in self.params: res = sc(code.ParamAbsence) res.result = res.result % p return res res = self.checkParamType("CDN", p) if isinstance(res, sc): return res if int(self.params["Version"]) != API_VERSION: res = sc(code.APIVersionError) res.result = res.result % self.params["Version"] return res if self.params["Action"] not in bgpParams.ActionParams: res = sc(code.NoThisAction) return res for p in bgpParams.ActionParams[self.params["Action"]]: res = self.checkActionParams(self.params["Action"], p) if isinstance(res, sc): return res return True
def checkPackageIDUserID(self): j = 'IPUserID' k = 'PackageID' if j in self.params and k in self.params: user_org = self.get_argument('AccessKeyId') v = self.get_argument(k) b = self.get_argument(j) sql = 'select 1 from t_package_protect where package_protect_id=%s and user_org=%s and user_end=%s;' data = self.application.dbcur.queryall_dict(sql, (v, user_org, b)) if data: return True else: res = sc(code.PermissionDenied) res.result = res.result % b return res