def test_HTTPSDistributor_getBridges_ipv4(self): """A request for IPv4 bridges should return IPv4 bridges.""" dist = distributor.HTTPSDistributor(1, self.key) [dist.insert(bridge) for bridge in self.bridges[:250]] for i in xrange(500): bridgeRequest = self.randomClientRequest() bridgeRequest.generateFilters() bridges = dist.getBridges(bridgeRequest, "faketimestamp") self.assertTrue(type(bridges) is list) self.assertGreater(len(bridges), 0) bridge = random.choice(bridges) bridgeLine = bridge.getBridgeLine(bridgeRequest) addrport, fingerprint = bridgeLine.split() address, port = addrport.rsplit(':', 1) self.assertIsInstance(ipaddr.IPAddress(address), ipaddr.IPv4Address) self.assertIsNotNone(byIPv4(random.choice(bridges)))
def setDhcpServerAddress(self, user): self.authUser(user) ip = self.netAddress.split(".") ip[3] = str(int(ip[3]) + 1) networkString = "%s/%s" % (self.netAddress, self.netMask) net = ipaddr.IPNetwork(networkString) ipAddr = ".".join(ip) ip = ipaddr.IPAddress(ipAddr) dhcpAddress = self.getDhcpServerAddress(user) if ip in net: ipString = "%s/%s" % (str(ip), str(self.netMask)) if dhcpAddress != None: dhcpAddress.isDhcpAddress = False dhcpAddress = dissomniag.model.IpAddress(user, ipString, isDhcpAddress=True, net=self) dhcpAddress.isDhcpAddress = True return dhcpAddress
def clean_host(self): host = self.cleaned_data['host'] addr_type = self.cleaned_data['addr_type'] if host: match = re.match(FQDN_RE, host) if not match: try: if addr_type == 'any': address = ipaddr.IPAddress(host) if addr_type == 'ipv4': address = ipaddr.IPv4Address(host) if addr_type == 'ipv6': address = ipaddr.IPv6Address(host) except Exception: error_text = _('Invalid network address/hostname format') raise forms.ValidationError(error_text) else: raise forms.ValidationError(_('This field is required.')) return self.cleaned_data["host"]
def withoutBlockInCountry(self, request): """Determine which countries the bridges for this **request** should not be blocked in. .. note:: Currently, a **request** for unblocked bridges is recognized if it contains an HTTP GET parameter ``unblocked=`` whose value is a comma-separater list of two-letter country codes. Any two-letter country code found in the :api:`request <twisted.web.http.Request>` ``unblocked=`` HTTP GET parameter will be added to the :data:`notBlockedIn` list. If :data:`addClientCountryCode` is ``True``, the the client's own geolocated country code will be added to the to the :data`notBlockedIn` list. :type request: :api:`twisted.web.http.Request` :param request: A ``Request`` object containing the HTTP method, full URI, and any URL/POST arguments and headers present. """ countryCodes = request.args.get("unblocked", list()) for countryCode in countryCodes: try: country = UNBLOCKED_PATTERN.match(countryCode).group() except (TypeError, AttributeError): pass else: if country: self.notBlockedIn.append(country.lower()) logging.info( "HTTPS request for bridges not blocked in: %r" % country) if self.addClientCountryCode: # Look up the country code of the input IP, and request bridges # not blocked in that country. if addr.isIPAddress(self.client): country = geo.getCountryCode(ipaddr.IPAddress(self.client)) if country: self.notBlockedIn.append(country.lower()) logging.info( ("HTTPS client's bridges also shouldn't be blocked " "in their GeoIP country code: %s") % country)
def get_xor_address(self, attr_type): addr_attr = self.find(attr_type) if not addr_attr: return None padding, family, xport, xaddr = unpack(addr_attr.data, self.__xor_v4addr_fmt) addr_ctor = IPv4Address if family == IPV6: from twisted.internet.address import IPv6Address padding, family, xport, xaddr = unpack(addr_attr.data, self.__xor_v6addr_fmt) addr_ctor = IPv6Address elif family != IPV4: raise ValueError("Invalid family: {}".format(family)) return addr_ctor('UDP', str(ipaddr.IPAddress(self.get_xaddr(xaddr, family))), self.get_xport(xport))
def parse_connection(self, conf, connection_root): if connection_root.tag == "Standard_Partition": connection_port = conf.get_port_by_partition_and_name( connection_root.attrib["PartitionName"], connection_root.attrib["PortName"]) return chpok_configuration.LocalConnection(connection_port) elif connection_root.tag == "UDP": res = chpok_configuration.UDPConnection() #print('ipaddr: ', root.attrib['IP']) res.host = ipaddr.IPAddress(root.attrib["IP"]) res.port = int(root.attrib["Port"]) return res else: raise RuntimeError("unknown connection tag name %r" % connection_root.tag)
def checkFreeAddress(self, user, address): self.authUser(user) netString = ("%s/%s" % (self.netAddress, self.netMask)) self.net = ipaddr.IPNetwork(netString) if not isinstance(address, ipaddr.IPv4Address): address = ipaddr.IPAddress(address) if not address in self.net: return False for addr in self.ipAddresses: if str(addr.addr) == str(address): return False dhcpNet = self.getDhcpSubnet(user) if dhcpNet != None and address in dhcpNet: return False return True
def service_resolved(self, interface, protocol, name, typ, domain, host, aprotocol, address, port, txt, flags): attributes = [] for attribute in txt: key, value = u"".join(map(chr, (c for c in attribute))).split("=") attributes.append("{key} = {value}".format(key=key, value=value)) text = unicode(attributes) print text sharename = u"{share} on {host}".format(share=name, host=host) _sharename = u"{share} on {host}: {txt}".format(share=name, host=host, txt=text) logging.debug("avahi-service resolved: %s" % _sharename) ip = ipaddr.IPAddress(address) if (len([ ip_range for ip_range in self.config.ip_whitelist if ip in ip_range ]) >= 1 and len([ ip_range for ip_range in self.config.ip_blacklist if ip in ip_range ]) == 0): if not sharename in self.linked: share = nfsService(config=config, interface=interface, protocol=protocol, name=name, typ=typ, domain=domain, host=host, aprotocol=aprotocol, address=address, port=port, txt=txt, flags=flags, sharename=sharename) self.linked[sharename] = share else: logging.debug("skipped share {0} on {1}: already used".format( name, host)) else: logging.debug( "skipped share {0} on {1}: IP {2} is set to be ignored".format( name, host, address))
def ip_range_applies(self, client_ip): """Checks to see whether the rule applies based on the client's IP address. If the rule has an associated IP range, it will check to see wether the client's IP falls within that range. If not, it's assumed that the rule applies. :param client_ip: the client's IP address. :type client_ip: str or ipaddr.IPv[46]Address :return: True if the rule applies for this check, otherwise False. """ if self.ip_range is None: return True if isinstance(client_ip, str): client_ip = ipaddr.IPAddress(client_ip) return (self.ip_range['start'] <= client_ip and self.ip_range['end'] >= client_ip)
def testbrutforcerun(conditions, ranges): result = [] found = 0 observed = 0 o = 0 for condition in conditions: regexp, prefix = condition for i3 in range(0, 256): for i4 in range(0, 256): s = "%s.%s.%s" % (prefix, i3, i4) o += 1 observed += 1 if o % 10000 == 0: print "Observed/Found: %s / %s" % (observed, found) o = 0 if int(ipaddr.IPAddress(s)) in ranges: found += 1 result.append(s) return result
def main(): desc = ( 'Measure compile time' ) usage = ( '%prog [options]\n' '(type %prog -h for details)' ) op = OptionParser( description=desc, usage=usage ) # Options op.add_option( '--num', '-n', action="store",\ dest="num_events", help = 'Number of events' ) if len(sys.argv) != 3: print "Wrong number of arguments" op.print_help() sys.exit() # Parsing and processing options, args = op.parse_args() # Events and values ev_tuple_list = [] ev_tuple_list.append(('authenticated','True')) # ev_tuple_list.append(('infected','True')) # Set starting IP address the_IP = ipaddr.IPAddress('1.1.1.1') # Start sending events for i in range(int(options.num_events)): for j in ev_tuple_list: cmd = BASE_CMD + "-n " + j[0] + " -l " + j[1] + " --flow='{srcip="+str(the_IP)+"}'" p = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True) out, err = p.communicate() the_IP = the_IP + 1 if str(the_IP).endswith('0') or str(the_IP).endswith('255'): the_IP = the_IP + 1 # End and flush. end_cmd = "python ../../json_sender.py -a 127.0.0.1 -p 50001 -n endofworld -l True --flow='{srcip=1.1.1.1}'" p = subprocess.Popen(end_cmd, stdout=subprocess.PIPE,shell=True) out, err = p.communicate()
def __init__(self, bindstrings, interface, backend, whitelist, lock): self.bindstrings = bindstrings self.interface = interface self.backend = backend self.ban_object = banobjects.entries[backend] self.whitelist = {"networks": [], "addresses": []} for entry in whitelist: if "/" in entry: # This check sucks but it'll do for now. ipaddr will # throw a suitable exception if this doesn't work self.whitelist["networks"].append(ipaddr.IPNetwork(entry)) else: self.whitelist["addresses"].append(ipaddr.IPAddress(entry)) self.sockets = {} for bindstring in bindstrings: context = zmq.Context() self.sockets[bindstring] = context.socket(zmq.SUB) subscriber = zmqstream.ZMQStream(self.sockets[bindstring]) if hasattr(zmq, "RCVHWM"): self.sockets[bindstring].setsockopt(zmq.RCVHWM, 2000) if hasattr(zmq, "SNDHWM"): self.sockets[bindstring].setsockopt(zmq.SNDHWM, 2000) if hasattr(zmq, "HWM"): self.sockets[bindstring].setsockopt(zmq.HWM, 2000) # SWAP is removed in zmq :( if hasattr(zmq, "SWAP"): self.sockets[bindstring].setsockopt(zmq.SWAP, 200 * 2**10) self.sockets[bindstring].setsockopt(zmq.SUBSCRIBE, "swabber_bans") self.sockets[bindstring].connect(bindstring) subscriber.on_recv(self.subscription) self.iptables_lock = lock threading.Thread.__init__(self) self.daemon = True
def validate_system_create_form(request): system = None post_data = copy(request.POST) if not post_data.get('ctnr'): post_data['ctnr'] = request.session['ctnr'].id system_form = ExtendedSystemForm(post_data) if system_form.is_valid(): system = system_form.save() post_data['system'] = system.id else: return HttpResponse(json.dumps({'errors': system_form.errors})) if post_data.get('interface_type', None) == 'static_interface': try: post_data['ip_type'] = ipaddr.IPAddress( post_data.get('ip_str', None)).version except: post_data['ip_type'] = None form = StaticInterfaceForm(post_data) else: form = DynamicInterfaceForm(post_data) if form.is_valid(): try: form.save() return HttpResponse( json.dumps({ 'success': True, 'system_id': system.id })) except ValidationError as e: if form.errors is None: form.errors = ErrorDict() form.errors.update(e.message_dict) return HttpResponse(json.dumps({'errors': form.errors})) else: if system: system.delete() return HttpResponse(json.dumps({'errors': form.errors}))
def testHash(self): self.assertEqual(hash(ipaddr.IPNetwork('10.1.1.0/24')), hash(ipaddr.IPNetwork('10.1.1.0/24'))) self.assertEqual(hash(ipaddr.IPAddress('10.1.1.0')), hash(ipaddr.IPAddress('10.1.1.0'))) # i70 self.assertEqual( hash(ipaddr.IPAddress('1.2.3.4')), hash(ipaddr.IPAddress(long(ipaddr.IPAddress('1.2.3.4')._ip)))) ip1 = ipaddr.IPAddress('10.1.1.0') ip2 = ipaddr.IPAddress('1::') dummy = {} dummy[self.ipv4] = None dummy[self.ipv6] = None dummy[ip1] = None dummy[ip2] = None self.assertTrue(self.ipv4 in dummy) self.assertTrue(ip2 in dummy)
def get(self, request): print(request.headers) print(request.META) print(request.build_absolute_uri()) print(request.build_absolute_uri("server")) print(request.build_absolute_uri("http://10.65.5.157")) print(request.get_full_path_info()) print(request.get_full_path()) print(request.get_port()) ip1 = "10.10.0.5" ip2 = "10.10.0.0/24" ip = ipaddr.IPAddress(ip1) # 单个ipv4地址对象建立 ip4 = ipaddr.IPv4Network(ip2) # ipv4网段对象建立 # ip6 = ipaddr.IPv6Network() # ipv6网段对象建立 ipd = ipaddr.IPNetwork(ip2) print(type(ip)) # IPAddress类型 print(type(ip4)) # IPv4Network print(type(ipd)) # IPNetwork # 广播地址 print(ip4.broadcast) # 10.10.0.255 # 掩码 print(ip4.hostmask) # 0.0.0.255 # ip数量 print(ip4.numhosts) # 256 # 创建一个网段中一个IP地址列表的迭代器对象 print(ip4.iterhosts()) # ip的字符串列表 print([v.__str__() for v in ip4.iterhosts()]) # ["10.10.0.0","10.10.0.1] # 网段中是否包含某个ip或网段,此ip要是addr对象,不是字符串 print(ip4.Contains(ip)) print(ip4.Contains(ip4)) # 是否是内网地址 print(ip.is_private) # 是否是loop地址 print(ip.is_loopback) # ip对象转为数值 print(ip.__int__()) return JsonResponse(data={"a": 1, "b": 2}, safe=False)
def RetrieveIPInfo(self, ip): if not ip: return (IPInfo.UNKNOWN, "No ip information.") ip_str = utils.SmartStr(ip) try: return self.cache.Get(ip_str) except KeyError: pass try: ip = ipaddr.IPAddress(ip_str) except ValueError: return (IPInfo.UNKNOWN, "No ip information.") if ip.version == 6: res = self.RetrieveIP6Info(ip) else: res = self.RetrieveIP4Info(ip) self.cache.Put(ip_str, res) return res
def clean_content(self): type = self.cleaned_data['type'] content = self.cleaned_data['content'] if type == 'CNAME': if content not in self.hostnames: raise forms.ValidationError("Invalid hostname for this device.") return validate_domain_name(content) elif type == 'A': try: address = ipaddr.IPAddress(content) except ValueError: raise forms.ValidationError("Invalid IP address") if self.is_extra: for r in Record.objects.filter(type='A', content=address): raise forms.ValidationError( "There is already an A DNS record for this IP " "(%s)." % r.name ) return unicode(address) return content
def get_xor_address(self, attr_type): addr_attr = self.find(attr_type) if not addr_attr: return None padding, family, xport, xaddr = unpack(addr_attr.data, self.__v4addr_fmt) addr_ctor = IPv4Address if family == STUN_IPV6: padding, family, xport, xaddr = unpack(addr_attr.data, self.__v6addr_fmt) addr_ctor = IPv6Address elif family != STUN_IPV4: raise ValueError("Invalid family: {}".format(family)) return addr_ctor( "UDP", str(ipaddr.IPAddress(self.get_xaddr(xaddr, family))), self.get_xport(xport), )
def verify(cls, request): request_ip = ipaddr.IPAddress(request.META["REMOTE_ADDR"]) if not (request_ip in ipaddr.IPNetwork("91.232.230.0/23") or request_ip in ipaddr.IPNetwork("79.142.16.0/20")): return False dig = hmac.new(settings.QIWI_SECRET, msg=u"|".join([ request.POST["amount"], request.POST["bill_id"], request.POST["ccy"], request.POST["command"], request.POST["comment"], request.POST["error"], request.POST["prv_name"], request.POST["status"], request.POST["user"] ]).encode("utf-8"), digestmod=hashlib.sha1).digest() return request.META.get("HTTP_X_API_SIGNATURE") == base64.b64encode( dig)
def __is_trusted_network(self): if self.__config.has_option("automx", "rate_limit_exception_networks"): networks = self.__config.get("automx", "rate_limit_exception_networks") networks = self.__config.create_list(networks) else: networks = ("127.0.0.1", "::1/128") for network in iter(networks): a = ipaddr.IPAddress(self.__client) n = ipaddr.IPNetwork(network) if n.Contains(a): if self.__config.debug: logging.debug("FOUND %s, %s" % (a, n)) return True else: if self.__config.debug: logging.debug("NOT FOUND %s, %s" % (a, n)) return False
def parse_device_desc_xml(filename): root = ET.parse(filename).getroot() (lo_prefix, mgmt_prefix, hostname, hwsku, d_type, _) = parse_device(root) results = {} results['DEVICE_METADATA'] = { 'localhost': { 'hostname': hostname, 'hwsku': hwsku, } } results['LOOPBACK_INTERFACE'] = {('lo', lo_prefix): {}} mgmt_intf = {} mgmtipn = ipaddress.IPNetwork(mgmt_prefix) gwaddr = ipaddress.IPAddress(int(mgmtipn.network) + 1) results['MGMT_INTERFACE'] = {('eth0', mgmt_prefix): {'gwaddr': gwaddr}} return results
def setUpClass(cls): super(GRRHTTPServerTest, cls).setUpClass() # Bring up a local server for testing. port = portpicker.pick_unused_port() ip = utils.ResolveHostnameToIP("localhost", port) cls.httpd = frontend.GRRHTTPServer((ip, port), frontend.GRRHTTPServerHandler) if ipaddr.IPAddress(ip).version == 6: cls.address_family = socket.AF_INET6 cls.base_url = "http://[%s]:%d/" % (ip, port) else: cls.address_family = socket.AF_INET cls.base_url = "http://%s:%d/" % (ip, port) cls.httpd_thread = threading.Thread( name="GRRHTTPServerTestThread", target=cls.httpd.serve_forever) cls.httpd_thread.daemon = True cls.httpd_thread.start()
def _ResolveAddress(self, resources, args, scope, forwarding_rule_ref): # Address takes either an ip address or an address resource. If parsing as # an IP address fails, then we resolve as a resource. address = args.address if address is not None: try: ipaddr.IPAddress(args.address) except ValueError: # TODO(b/37086838): Make sure global/region settings are inherited by # address resource. if scope == compute_flags.compute_scope.ScopeEnum.REGION: if not args.global_address and not args.address_region: if forwarding_rule_ref.Collection( ) == 'compute.forwardingRules': args.address_region = forwarding_rule_ref.region address_ref = flags.ADDRESS_ARG.ResolveAsResource( args, resources, default_scope=scope) address = address_ref.SelfLink() return address
def testGetAddrFromFleetspeakIpV6(self): client_id = client_plugin.ApiClientId("C." + "1" * 16) conn = mock.MagicMock() conn.outgoing.ListClients.return_value = admin_pb2.ListClientsResponse( clients=[ admin_pb2.Client( client_id=fleetspeak_utils.GRRIDToFleetspeakID(client_id), last_contact_address= "[2001:0db8:85a3::8a2e:0370:7334]:50000", last_contact_time=TSProtoFromString( "2018-01-01T00:00:01Z"), last_clock=TSProtoFromString("2018-01-01T00:00:02Z")) ]) with mock.patch.object(fleetspeak_connector, "CONN", conn): ip_str, ipaddr_obj = client_plugin._GetAddrFromFleetspeak( client_id) self.assertEqual(ip_str, "2001:0db8:85a3::8a2e:0370:7334") self.assertEqual( ipaddr_obj, ipaddr.IPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"))
def get_gateway_ip(self, index=0): """ Returns the ip of the gateway. :rtype: An IPv4Address or IPv6Address object. """ gateways = self.get_gateways() leap_assert(len(gateways) > 0, "We don't have any gateway!") if index > len(gateways): index = 0 logger.warning("Provided an unknown gateway index %s, " + "defaulting to 0") ip_addr_str = gateways[index]["ip_address"] try: ipaddr.IPAddress(ip_addr_str) return ip_addr_str except ValueError: logger.error("Invalid ip address in config: %s" % (ip_addr_str, )) return None
def getClientIP(self, request): """Get the client's IP address from the :header:`X-Forwarded-For` header, or from the :api:`request <twisted.web.server.Request>`. :rtype: None or str :returns: The client's IP address, if it was obtainable. """ ip = None if self.useForwardedHeader: header = request.getHeader("X-Forwarded-For") if header: ip = header.split(",")[-1].strip() try: ipaddr.IPAddress(ip) except ValueError: logging.warn("Got weird X-Forwarded-For value %r" % header) ip = None else: ip = request.getClientIP() return ip
def _gather_test_params(tbinfo, duthost, request): """ Fetches the test parameters from pytest. """ swap_syncd = request.config.getoption("--copp_swap_syncd") topo = tbinfo["topo"]["name"] mg_facts = duthost.get_extended_minigraph_facts(tbinfo) port_index_map = { k: v for k, v in mg_facts["minigraph_port_indices"].items() if k in mg_facts["minigraph_ports"] } nn_target_port = port_index_map[random.choice(port_index_map.keys())] nn_target_interface = copp_utils._map_port_number_to_interface( duthost, nn_target_port) myip = None peerip = None for bgp_peer in mg_facts["minigraph_bgp"]: if bgp_peer["name"] == mg_facts["minigraph_neighbors"][ nn_target_interface]["name"] and ipaddr.IPAddress( bgp_peer["addr"]).version == 4: myip = bgp_peer["addr"] peerip = bgp_peer["peer_addr"] break nn_target_namespace = mg_facts["minigraph_neighbors"][nn_target_interface][ 'namespace'] logging.info( "nn_target_port {} nn_target_interface {} nn_target_namespace {}". format(nn_target_port, nn_target_interface, nn_target_namespace)) return _COPPTestParameters(nn_target_port=nn_target_port, swap_syncd=swap_syncd, topo=topo, myip=myip, peerip=peerip, nn_target_interface=nn_target_interface, nn_target_namespace=nn_target_namespace)
def main(_): """Run the main test harness.""" config_lib.CONFIG.AddContext( "AdminUI Context", "Context applied when running the admin user interface GUI.") startup.Init() # Start up a server in another thread bind_address = config_lib.CONFIG["AdminUI.bind"] ip = ipaddr.IPAddress(bind_address) if ip.version == 4: # Address looks like an IPv4 address. ThreadingDjango.address_family = socket.AF_INET # Make a simple reference implementation WSGI server server = simple_server.make_server(bind_address, config_lib.CONFIG["AdminUI.port"], django_lib.GetWSGIHandler(), server_class=ThreadingDjango) proto = "HTTP" if config_lib.CONFIG["AdminUI.enable_ssl"]: cert_file = config_lib.CONFIG["AdminUI.ssl_cert_file"] if not cert_file: raise ValueError("Need a valid cert file to enable SSL.") key_file = config_lib.CONFIG["AdminUI.ssl_key_file"] server.socket = ssl.wrap_socket(server.socket, certfile=cert_file, keyfile=key_file, server_side=True) proto = "HTTPS" # SSL errors are swallowed by the WSGIServer so if your configuration does # not work, uncomment the line below, point your browser at the gui and look # at the log file to see why SSL complains: # server.socket.accept() sa = server.socket.getsockname() logging.info("Serving %s on %s port %d ...", proto, sa[0], sa[1]) server.serve_forever()
def dict2pb(d, pb): """ Convert dictionary to protobuf msg. Takes dict and protobuf message to be merged into. """ for field in pb.DESCRIPTOR.fields: if field.name not in d: continue value = d[field.name] if field.label == FD.LABEL_REPEATED: pb_val = getattr(pb, field.name, None) if is_string(value[0]) and _marked_as_ip(field): val = ipaddr.IPAddress(value[0]) if val.version == 4: pb_val.append(socket.htonl(int(val))) elif val.version == 6: ival = int(val) pb_val.append(socket.htonl((ival >> (32 * 3)) & 0xFFFFFFFF)) pb_val.append(socket.htonl((ival >> (32 * 2)) & 0xFFFFFFFF)) pb_val.append(socket.htonl((ival >> (32 * 1)) & 0xFFFFFFFF)) pb_val.append(socket.htonl((ival >> (32 * 0)) & 0xFFFFFFFF)) else: raise Exception("Unknown IP address version %d" % val.version) continue for v in value: if field.type == FD.TYPE_MESSAGE: dict2pb(v, pb_val.add()) else: pb_val.append(_dict2pb_cast(field, v)) else: if field.type == FD.TYPE_MESSAGE: # SetInParent method acts just like has_* = true in C, # and helps to properly treat cases when we have optional # field with empty repeated inside. getattr(pb, field.name).SetInParent() dict2pb(value, getattr(pb, field.name, None)) else: setattr(pb, field.name, _dict2pb_cast(field, value)) return pb
def add(): print(request.json) if not request.json: return "Fail", 401 uid = request.json["uid"].lower() if not len(uid) == 36: return "Not a valid length", 402 abort(401) try: uuid.UUID(uid) except ValueError: return "Not a UUID", 402 abort(401) test = request.json["test"] if not test.isdigit(): return "test is not a digit", 402 abort(401) result = request.json["result"] testresult = result.split(',') for ip in testresult: try: _ipv4 = ipaddr.IPAddress(ip) except: return "not a valid IP. Try a valid one", 402 abort(401) if True: # Todo add validation dbrec = DBPREFIX % uid exists = r.hget(dbrec, test) # find out if the rec exists if exists: print("Existing record found for %s" % uid) r.hset(dbrec, int(test), result) else: print("Adding new record for: %s" % uid) # Add the first url found #r.setex(A_RECORD_PREFIX % qname, peer[0], 30) #r.setex(DBPREFIX % uid + ':00', peer[0], 30) r.hset(dbrec, int(test), result) return "Successfully added %s" % result, 201 else: return "Invalid test results", 500