def guest_portal(sitekey): #--get all URL parameters, expected URL format-- devicemac = request.args.get('id') apmac = request.args.get('ap') origurl = request.args.get('url') demo = request.args.get('demo') utcnow = arrow.utcnow().naive if not devicemac or not apmac: logger.error("Guest portal called with empty ap_mac/user_mac URL:%s"\ %request.url) abort(404) if not validators.mac_address(devicemac) or not validators.mac_address(apmac): logger.error("Guest portal called with invalid ap_mac/user_mac URL:%s"%\ request.url) abort(404) wifisite = Wifisite.query.filter_by(sitekey=sitekey).first() if not wifisite: logger.error("Guest portal called with unknown UnifiID URL:%s"%request.url) abort(404) if demo and current_user.is_authenticated: demo = 1 else: demo = 0 guesttrack = init_track(wifisite,devicemac,apmac,origurl,demo) return redirect_guest(wifisite,guesttrack)
def mac_vendor(ip): # set api url url = "https://api.macvendors.com/" vendor = "Could not get" try: # get mac address from ip, via passive arp scanning (no network request) mac = str(getmac.get_mac_address(ip=str(ip), network_request=False)) logging.info("The mac address of the machine is: " + mac) # check mac address if validators.mac_address(mac): try: # Make a get request to get response from the macvendors api response = requests.get(url + mac) # set response to variable vendor = response.content.decode("utf-8") except Exception as e: logging.warning( "The following error raise when trying to get response from macvendors.com:" + str(e)) else: logging.warning("The MAC address of the machine is not valid") except Exception as e: logging.warning( "The following error raise when trying to get the MAC address from the network machine:" + str(e)) return str(vendor)
def add_nic(self, nic_name, mac_or_pattern, ip_or_index, net, on_wires): import validators from lab.network import Nic ip_or_index = ip_or_index or self._assign_default_ip_index(net) try: index = int(ip_or_index) # this is shift in the network if index in [0, 1, 2, 3, -1]: raise ValueError('{}: index={} is not possible since 0 => network address [1,2,3] => GW addresses -1 => broadcast address'.format(self.get_id(), index)) try: ip = net[index] except (IndexError, ValueError): raise ValueError('{}: index {} is out of bound of {}'.format(self.get_id(), index, net)) except ValueError: if validators.ipv4(str(ip_or_index)): try: index, ip = {x: str(net[x]) for x in range(net.size) if str(ip_or_index) in str(net[x])}.items()[0] except IndexError: raise ValueError('{}: ip {} is out of bound of {}'.format(self.get_id(), ip_or_index, net)) else: raise ValueError('{}: specified value "{}" is neither ip nor index in network'.format(self.get_id(), ip_or_index)) self.lab().make_sure_that_object_is_unique(obj=ip, node_id=self.get_id()) mac = mac_or_pattern if validators.mac_address(str(mac_or_pattern)) else self.form_mac(mac_or_pattern) self.lab().make_sure_that_object_is_unique(obj=mac, node_id=self.get_id()) nic = Nic(name=nic_name, mac=mac, node=self, net=net, net_index=index, on_wires=on_wires) self._nics[nic_name] = nic return nic
def check_macaddress(macaddress): if validators.mac_address(macaddress) != True: print "The macaddress " + macaddress + " specified is not rfc compliant" return False else: return True
def validate_web_domain(domain): is_public_url = validators.url("http://" + domain, public=True) is_public_tld = len(tldextract.extract(domain).suffix) > 0 is_valid_domain = validators.domain(domain) is_ipv4_address = validators.ip_address.ipv4(domain) is_ipv6_address = validators.ip_address.ipv6(domain) is_mac_address = validators.mac_address(domain) return is_public_url and is_public_tld and is_valid_domain and not is_ipv4_address and not is_ipv6_address and not is_mac_address
def is_valid_mac_address(mac_address): """ Check if MAC address is valid. Example: 00:11:22:33:44:55 """ if validators.mac_address(mac_address): return True return False
def determine_resource_type(value): if validators.ipv4(value) or validators.ipv6(value): return 'ip' if validators.domain(value): return 'domain' if validators.email(value): return 'email' if validators.mac_address(value): return 'mac_address'
def mac_address(value): """ Validate whether or not the given string is a valid MAC address. Args: value (str): the value to validate. Raises: ValidationError: when the value is not a valid MAC address. """ if not validators.mac_address(value): raise ValidationError('{!r} is not a valid MAC address'.format(value))
def guest_portal(sitekey): #--get all URL parameters, expected URL format-- devicemac = request.args.get('id') apmac = request.args.get('ap') visitedurl = request.args.get('url') demo = request.args.get('demo') utcnow = arrow.utcnow().naive ua = request.headers.get('User-Agent') if ua and 'CaptiveNetworkSupport' in ua: current_app.logger.debug( 'Detected apple CNA, sending our ERROR response') return '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD> <TITLE>ERROR</TITLE></HEAD><BODY>ERROR</BODY></HTML>''' if not devicemac or not apmac: current_app.logger.error("Guest portal called with empty ap_mac/user_mac URL:%s"\ %request.url) abort(404) if not validators.mac_address(devicemac) or not validators.mac_address( apmac): current_app.logger.error("Guest portal called with invalid ap_mac/user_mac URL:%s"%\ request.url) abort(404) wifisite = Wifisite.query.filter_by(sitekey=sitekey).first() if not wifisite: current_app.logger.error( "Guest portal called with unknown UnifiID URL:%s" % request.url) abort(404) if demo and current_user.is_authenticated: demo = 1 else: demo = 0 guesttrack = init_track(wifisite, devicemac, apmac, visitedurl, demo) return redirect_guest(wifisite, guesttrack)
async def _main(script_path): # Check device argument if validators.ip_address.ipv4(args.device): # If the device is an IP adress, it's an EV3 Brick with ev3dev. hub = EV3Connection() address = args.device else: # Otherwise it is a Pybricks Hub with device name or address given. hub = PUPConnection() if validators.mac_address(args.device): address = args.device else: address = await find_device(args.device, timeout=5) # Connect to the address and run the script await hub.connect(address) await hub.run(script_path) await hub.disconnect()
def add_device(): new_device_data = general_utils.read_device_details_from_request_body() mac = new_device_data['mac'] if len(mac) == 0: return jsonify(status="Error", reason="Must Supply MAC Address") if not validators.mac_address(mac): return jsonify(status="Error", reason="Invalid MAC Address") ip = new_device_data['ip'] if len(ip) > 0 and not validators.ip_address(ip): return jsonify(status="Error", reason="Invalid IP Address") hostname = new_device_data['hostname'] if len(hostname) > 0 and not validators.hostname(hostname): return jsonify(status="Error", reason="Invalid Hostname") existing_devices = db.find_device_by_mac(mac) if len(existing_devices) == 0: try: db.add_device(new_device_data) email_body = render_template('emails/addDevice.html', deviceInfo=new_device_data, serverUrl=app.config['SERVER_URL']) email.email_user("New Device Detected", email_body) return jsonify(status="Success", reason="Device added") except Exception as e: traceback.print_exc() return jsonify(status="Error", reason='Error adding device:' + str(e)) else: # device already exists existing_device = existing_devices[0] existing_device['hostname'] = hostname existing_device['ip'] = ip existing_device['last_seen'] = datetime.datetime.now() try: db.update_device(existing_device) return jsonify(status="Success", reason="Device updated") except Exception as e: traceback.print_exc() return jsonify(status="Error", reason='Error updating device:' + str(e))
async def run(self, args: argparse.Namespace): from ..ble import find_device from ..connections import PybricksHub, EV3Connection, USBPUPConnection, USBRPCConnection # Convert script argument to valid path script_path = _parse_script_arg(args.script) # Pick the right connection if args.conntype == 'ssh': # So it's an ev3dev if not validators.ip_address.ipv4(args.device): raise ValueError("Device must be IP address.") hub = EV3Connection() device_or_address = args.device elif args.conntype == 'ble': # It is a Pybricks Hub with BLE. Device name or address is given. hub = PybricksHub() hub.logger.setLevel(logging.WARNING) if validators.mac_address(args.device): device_or_address = args.device else: device_or_address = await find_device(args.device, timeout=5) elif args.conntype == 'usb' and args.device == 'lego': # It's LEGO stock firmware Hub with USB. hub = USBRPCConnection() hub.logger.setLevel(logging.INFO) device_or_address = 'LEGO Technic Large Hub in FS Mode' elif args.conntype == 'usb': # It's a Pybricks Hub with USB. Port name is given. hub = USBPUPConnection() hub.logger.setLevel(logging.INFO) device_or_address = args.device else: raise ValueError(f"Unknown connection type: {args.conntype}") # Connect to the address and run the script await hub.connect(device_or_address) try: await hub.run(script_path, args.wait == 'True') finally: await hub.disconnect()
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup""" _LOGGER.debug("Starting up") import validators if DATA_ARPSPOOF not in hass.data: _LOGGER.error("ARP component not initialised!") return False devices = config.get(CONF_DEVICES, {}) switches = [] data = hass.data[DATA_ARPSPOOF] for object_id, device_config in devices.items(): address = device_config.get(CONF_ADDRESS) friendly_name = device_config.get(CONF_FRIENDLY_NAME) type = -1 if validators.ipv4(address): type = 0 elif validators.mac_address(address): type = 1 if type > -1: _LOGGER.debug("Adding '%s' as switch '%s'", address, friendly_name) switches.append( ArpSpoofSwitch(data, object_id, friendly_name, address, type, device_config.get(CONF_ICON))) else: _LOGGER.debug("Address '%s' is not valid IP or MAC", address) if not switches: _LOGGER.error("No devices added") return False add_devices(switches)
def _get_payload(self, params): agent = params.get(Input.AGENT) if params.get(Input.QUARANTINE_STATE, True): action = "cmd_isolate_agent" else: action = "cmd_restore_isolated_agent" if "cmd_isolate_agent" == action and agent in params.get( Input.WHITELIST, []): raise PluginException( cause="Unable to block whitelisted entry.", assistance= f"Please remove the host from the action's whitelist or quarantine a different host.", ) payload = {"act": action, "allow_multiple_match": True} validate_dict = { "entity_id": validators.uuid, "ip_address": lambda address: (validators.ipv4(address) or validators.ipv6(address)), "host_name": self.validate_host_name, } if validators.mac_address(agent.replace("-", ":")): payload["mac_address"] = agent else: for name, validate_fn in validate_dict.items(): if validate_fn(agent): payload[name] = agent break return payload
def test_returns_true_on_valid_mac_address(address): assert mac_address(address)
def verify_mac_address_format(mac_address): if not mac_address: return False return validators.mac_address(mac_address)
def test_returns_failed_validation_on_invalid_mac_address(address): assert isinstance(mac_address(address), ValidationFailure)
def validateMac(address): if mac_address(address): return address raise ValueError('"' + address + '" is not a valid MAC address')
def validate_mac(mac: str) -> None: if mac_address(mac) is not True: raise ValidationError(f'"{mac}" is not a valid mac')
ip = rootip path = [] printmul(f"""\ target MAC: {target} root: {root} Start """) while (ip): ip = hop(ip, target, path) print('---') print('Done') if __name__ == '__main__': parser = ArgumentParser(description="Trace REDACTED stuff") parser.add_argument('-c', '--community', help='SNMP community', default='public') parser.add_argument('target', help='target MAC address') args = parser.parse_args() validators.mac_address(args.target) # TODO: use getpass module or *.ini # for acquiring community community = args.community run(args.target)
def main (): mac=ip=switch=interface=vrf=count=source = '' parser = argparse.ArgumentParser(usage='%(prog)s -a [action] -l [location] [optional arguments]', formatter_class=argparse.RawTextHelpFormatter) required = parser.add_argument_group('Required', 'Required Arguments') required.add_argument("-a", action="store", dest="action", required=True, help="""[ping|test_cable|int_config|qos_stats|bounce|find] ping - Ping device from Core Switch. test_cable - Run cable test from switch. int_config - Display interface configuration. qos_stats - Display QoS statistics from interface. int_stats - Display Interface statistics. bounce - Bounve switch interface. find - Find endpoint in the Network. find_errors - Find Interfaces in the Network with errors. find_drops - Find Interfaces in the Network with dropped packets.""") required.add_argument("-l", action="store", dest="location", required=True, help="ISE deployment witch to connect.") optional = parser.add_argument_group('Optional', 'Optional Arguments') optional.add_argument("-mac", action="store", dest="mac", help="Endpoint MAC Address. ") optional.add_argument("-ip", action="store", dest="ip", help="Endpoint IP Address. ") optional.add_argument("-sw", action="store", dest="switch", help="Switch IP Address. ") optional.add_argument("-int", action="store", dest="interface", help="Interface Name. ") optional.add_argument("-vrf", action="store", dest="vrf", help="VRF Name to source PING. ") optional.add_argument("-c", action="store", dest="count", help="Amount of PING packets. ") optional.add_argument("-src", action="store", dest="source", help="Source Interface for PING. ") options = parser.parse_args() if options.location: define_network_variables(options.location) if options.mac: if validators.mac_address(options.mac): mac = options.mac else: print ("Invalid MAC Address! ") sys.exit() if options.ip: if validators.ipv4(options.ip): ip = options.ip else: print ("Invalid IP Address! ") sys.exit() if options.switch: i=0 if validators.ipv4(options.switch): switch = options.switch for device in switches: if device['switch_ip'] == switch: i =1 if i != 1: print ("Switch IP Address, does not exist in this location!") sys.exit() else: print ("Invalid Switch IP Address! ") sys.exit() if options.interface: interface = validate_interface(options.interface) if options.source: source = options.source if options.vrf: vrf = options.vrf if options.count: count = options.count if options.action: if options.action == 'ping': if ip: ping_result = '{}' ping_result_json = json.loads(ping_result) if switch: ping_result_json[switch] = ping_test(switch,ip,source,vrf,count) #print(ping_result_json) print(json.dumps(ping_result_json, indent=4, sort_keys=True)) else: for i in switches: if i['switch_group'] == "core": ping_result_json[i['switch_ip']] = ping_test(i['switch_ip'],ip,source,vrf,count) #print(ping_result_json) print(json.dumps(ping_result_json, indent=4, sort_keys=True)) else: print ("Invalid Options! ping requires -ip. Addtional options -sw, -vrf, -src, -c are optional.") sys.exit() elif options.action == 'test_cable': if switch and interface: test_result = cable_test(switch,interface) print(json.dumps(test_result, indent=4, sort_keys=True)) #print(test_result) else: print ("Invalid Options! Cable test requires -sw and -int options.") sys.exit() elif options.action == 'int_config': if switch and interface: result_int_config = interface_run_config(switch,interface) result = '{}' result_json = json.loads(result) for i in result_int_config: result_json[interface] = result_int_config[i] print(json.dumps(result_json, indent=4, sort_keys=True)) else: print ("Invalid Options! Show run Interface config requires -sw and -int options.") sys.exit() elif options.action == 'qos_stats': if switch and interface: result_qos_stats = interface_qos_stats(switch,interface) result = '{}' result_json = json.loads(result) for i in result_qos_stats: result_json[interface] = result_qos_stats[i] print(json.dumps(result_json, indent=4, sort_keys=True)) else: print ("Invalid Options! QoS Statistics requires -sw and -int options.") sys.exit() elif options.action == 'arp': if switch: result_rest_arp = get_arp_cli(switch) print(json.dumps(result_rest_arp, indent=4, sort_keys=True)) else: print ("Invalid Options! Find endpoint requires -mac or -ip options.") sys.exit() elif options.action == 'int_stats': if switch and interface: result_int_stats = interface_stats(switch,interface) print(json.dumps(result_int_stats, indent=4, sort_keys=True)) #print(result_int_stats[interface]['counters']) else: print ("Invalid Options! Interface Statistics requires -sw and -int options.") sys.exit() elif options.action == 'bounce': if switch and interface: result_bounce = bounce_interface(switch,interface) print(result_bounce) else: print ("Invalid Options! Bounce requires -sw and -int options.") sys.exit() elif options.action == 'find': if mac or ip: if switch: if ip: ping_result = ping_test(switch,ip,source,vrf,count) arp_table[switch] = get_arp_cli(switch) mac_table[switch] = get_mac(switch) else: for i in switches: if ip: ping_result = ping_test(i['switch_ip'],ip,source,vrf,count) arp_table[i['switch_ip']] = get_arp_cli(i['switch_ip']) temp_table = get_mac(i['switch_ip']) mac_table[i['switch_ip']] = temp_table if i['switch_group'] == 'access': mac_table_access[i['switch_ip']] = temp_table if mac: result = find_device(mac,"mac") elif ip: result = find_device(ip,"ip") print(json.dumps(result, indent=4, sort_keys=True)) else: print ("Invalid Options! Find endpoint requires -mac or -ip options.") sys.exit() elif options.action == 'find_errors': result_int_error = '{}' result_int_error_json = json.loads(result_int_error) if switch: result_int_error_json[switch] = find_interface_errors(switch) print(json.dumps(result_int_error_json, indent=4, sort_keys=True)) else: for i in switches: result_int_error_json[i['switch_ip']] = find_interface_errors(i['switch_ip']) print(json.dumps(result_int_error_json, indent=4, sort_keys=True)) elif options.action == 'find_drops': result_int_drops = '{}' result_int_drops_json = json.loads(result_int_drops) if switch: result_int_drops_json[switch] = find_interface_drops(switch) print(json.dumps(result_int_drops_json, indent=4, sort_keys=True)) else: for i in switches: result_int_drops_json[i['switch_ip']] = find_interface_drops(i['switch_ip']) print(json.dumps(result_int_drops_json, indent=4, sort_keys=True)) else: print ("Invalid Action!") return
def mac_check(address): if validators.mac_address(str(address)): return True else: return False
def v_mac_address(self, key): return validators.mac_address(self.__dict__[key])
def validate_mac_address(mac_addr): return mac_address(mac_addr)
def arg_validator(arg, vlist=None): """ 检查数据,可对同一个数据进行多种检查 arg : 字符串,要验证的参数 vlist : 列表,验证列表,每个元素包含两项. 第一个项是检查类型(字符串),第二项是可选参数字典,类似: [ ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}), ... ] 返回: 双元组,第一项为True 或 False,第二项为验证失败的类型(第一项为True的话第二项就留空) 注意: vlist 列表的第一项可以是字符串 "required",用于表示是必填项: 如果第一项不是,而且要验证的 arg 为空,会直接返回 True,不是的继续验证。 如果第一项是,就完全按照 vlist[1:] 的要求验证 vlist 的元素如果是验证整数/小数/email等不需要附加参数的可以直接传入验证类型字符串即可 用例(使用args_validator函数的,看这里vdict每个键值对的形式): vdict = { "token": ["required", "uuid"], "username": ["required", ("length", {"min": 4, "max": 30}), "safe_str"], "password": ["required", ("length", {"min": 4, "max": 20}), "safe_str"], "captcha": ["required", ("length", {"min": 4, "max": 8}), "safe_str"], } form = args_validator(self.request.arguments, vdict) """ if not any((isinstance(vlist, list), isinstance(vlist, tuple))): einfo = "不支持的数据类型!应使用列表或元组,但输入的是{}".format(type(vlist)) raise ValueError(einfo) if vlist[0] == "required": # 第一项不是 required 的,把第一项的 "required" 去掉 vlist = vlist[1:] else: # 第一项不是 required 的,如果 arg 是空的,直接返回 True,不是的继续验证 if not arg: return True, None # 待返回的验证结果 verification = None failed_type = None # 验证失败的类型 # 开始检查,有一个不通过就返回 False for i in vlist: local_verification = None if isinstance(i, str): # 如果是字符串的话就改为元组 i = (i, {}) if len(i) == 1: # 只有一个元素的,添加一个空字典 i = (i[0], {}) vtype = i[0] # 检查类型是第一项 vdict = i[1] # 检查类型所需的可选参数字典 # 在 validators 之外添加的 # 没有空白 if vtype == "no_space": if not re.search(r"\s", arg): local_verification = True # 安全字符串,只包含 0-9a-zA-Z-空格和下划线 elif vtype == "safe_str": if re.match(r"^[0-9a-zA-Z-_ ]+$", arg, flags=re.U): local_verification = True # 是否包含 elif vtype == "in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg not in v: local_verification = False break elif vtype == "not_in": # 迭代 vdict 的键值(所以键名无所谓) for v in vdict.values(): if arg in v: local_verification = False break # 字符串形式的数字 elif vtype == "str_number": if re.match(r"[+-]?\d+$", arg, flags=re.U) or \ re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_int": if re.match(r"[+-]?\d+$", arg, flags=re.U): local_verification = True elif vtype == "str_float": if re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U): local_verification = True # 数字 elif vtype == "number": # 整数或浮点数都可以 local_verification = isinstance(arg, int) or isinstance(arg, float) elif vtype == "int": local_verification = isinstance(arg, int) elif vtype == "float": local_verification = isinstance(arg, float) # 直接调用 validators的 elif vtype == "length": local_verification = validators.length(arg, **vdict) elif vtype == "url": local_verification = validators.url(arg, **vdict) elif vtype == "email": local_verification = validators.email(arg, **vdict) elif vtype == "ip": # ipv4 或 ipv6都可以 local_verification = any((validators.ipv4(arg, **vdict), validators.ipv6(arg, **vdict))) elif vtype == "between": local_verification = validators.between(arg, **vdict) elif vtype == "uuid": local_verification = validators.uuid(arg, **vdict) elif vtype == "ipv4": local_verification = validators.ipv4(arg, **vdict) elif vtype == "ipv6": local_verification = validators.ipv6(arg, **vdict) elif vtype == "mac_address": local_verification = validators.mac_address(arg, **vdict) elif vtype == "iban": local_verification = validators.iban(arg, **vdict) elif vtype == "slug": local_verification = validators.slug(arg, **vdict) elif vtype == "truthy": local_verification = validators.truthy(arg, **vdict) # 对于验证不为真或没有验证的 # 不为真的时候返回的是: ValidationFailure(......) if not local_verification: verification = False failed_type = vtype break # 有一条不为 True, 直接返回 False else: verification = True # 处理返回值 if verification not in(False, True): verification = False if not verification: return verification, failed_type else: return True, None
aparser.add_argument('-c', '--comment', required=False, help="ticket information") # populate list with wlc ips wlcs = cparser.options('wlcs') # setup threadpool with max amount thread = ThreadPoolExecutor(max_workers=30) if len(sys.argv) == 1: print "Error: No arguments supplied\n" aparser.print_help() sys.exit(1) args = aparser.parse_args() # handle some user based arg errors if validators.mac_address(args.mac) is not True: print "Your MAC address appears invalid, closing" sys.exit(1) elif args.action == "block" and not args.comment: print "You selected block but comment is missing, closing" aparser.print_help() sys.exit(1) elif re.findall(r'unblock|search', args.action, re.IGNORECASE): args.comment = "" def log_print(output): syslog.openlog("nyu-mac-exclude") syslog.syslog(syslog.LOG_ALERT, output) print output def send_it(wlc, action, mac, comment):