def get_mac(): """Returns the device mac address in unix format @rtype: string @return: The mac address in unix format """ mac = EUI(getnode()) mac.dialect = mac_unix return str(mac)
def test_iab(): eui = EUI('00-50-C2-05-C0-00') assert eui.is_iab() assert str(eui.oui) == '00-50-C2' assert str(eui.iab) == '00-50-C2-05-C0-00' assert eui.ei == '05-C0-00' assert int(eui.oui) == 0x0050c2 assert int(eui.iab) == 0x0050c205c
async def test_model_with_macadressfield_field_ok(self): mac = "00-1B-77-49-54-FD" pub = Publisher(name="Linda", json={"last_name": "Olson"}, mac=mac) await pub.save() # diferent dialects self.assertNotEqual(pub.mac, mac) # equal when converted on same dialect self.assertEqual(str(EUI(pub.mac, dialect=mac_eui48)), mac) # equal before representation self.assertEqual(EUI(pub.mac), EUI(mac))
def to_python(self, value): value = super().to_python(value) # Validate MAC address format try: value = EUI(value.strip()) except AddrFormatError: raise forms.ValidationError(self.error_messages['invalid'], code='invalid') return value
def three_probes_per_second(probe_qs): qs = Probe.objects.none() for mac_address in set(probe_qs.values_list('source_address', flat=True)): for time in probe_qs.filter( source_address=EUI(mac_address)).values_list('time', flat=True): if probe_qs.filter(time=time, source_address=EUI(mac_address)).count() >= 3: qs = qs | probe_qs.filter(time=time) return qs
def validate_host(self, value): if value and not isinstance(value, Host): try: value = EUI(value, dialect=mac_unix_common) host = Host.objects.filter(pk=value).first() except (AddrFormatError, TypeError): host = Host.objects.filter(hostname=value.lower()).first() if not host: raise serializers.ValidationError('The hostname enetered does not exist. Please first create the host.') return host return None
def get_Interface_from_list(interfaces, mac): """Return the `Interface` object with the given MAC address.""" # Compare using EUI instances so that we're not concerned with a MAC's # canonical form, i.e. colons versus hyphens, uppercase versus lowercase. mac = EUI(mac) for interface in interfaces: ifmac = interface.mac_address if ifmac is not None and EUI(ifmac.raw) == mac: return interface else: return None
def test_mac_to_ipv6(): mac = EUI('00-1B-77-49-54-FD') eui = mac.eui64() assert mac == EUI('00-1B-77-49-54-FD') assert eui == EUI('00-1B-77-FF-FE-49-54-FD') assert mac.modified_eui64() == EUI('02-1B-77-FF-FE-49-54-FD') assert mac.ipv6_link_local() == IPAddress('fe80::21b:77ff:fe49:54fd') assert eui.ipv6_link_local() == IPAddress('fe80::21b:77ff:fe49:54fd') assert mac.ipv6(0x12340000000000000000000000000000) == IPAddress('1234::21b:77ff:fe49:54fd') assert eui.ipv6(0x12340000000000000000000000000000) == IPAddress('1234::21b:77ff:fe49:54fd')
def test_mac_to_eui64_conversion(): mac = EUI('00-1B-77-49-54-FD') assert mac == EUI('00-1B-77-49-54-FD') eui = mac.eui64() assert eui == EUI('00-1B-77-FF-FE-49-54-FD') eui.eui64() == EUI('00-1B-77-FF-FE-49-54-FD') assert int(eui) == 7731765737772285 assert eui.packed == b'\x00\x1bw\xff\xfeIT\xfd' assert eui.bin == '0b11011011101111111111111111110010010010101010011111101' assert eui.bits() == '00000000-00011011-01110111-11111111-11111110-01001001-01010100-11111101'
def startAccessFromMacAddress(request, minutes, mac_address): try: eui = EUI(mac_address) except AddrFormatError: messages.add_message(request, messages.ERROR, "Invalid MAC Address! Please check again.") else: eui.dialect = mac_unix eui.dialect.word_fmt = "%.2X" _sendRaw(eui, int(minutes)) messages.add_message(request, messages.SUCCESS, "Internet access started for %s!" % mac_address)
def get_prep_value(self, value): if value is None: return None if not isinstance(value, EUI): value = EUI(value, dialect=default_dialect()) if self.integer: return int(value) return str(value) value.dialect = default_dialect(self) if self.integer: return int(value) return str(value)
def test__bindings__returns_sender_and_target_for_reply(self): pkt_sender_mac = '01:02:03:04:05:06' pkt_sender_ip = '192.168.0.1' pkt_target_ip = '192.168.0.2' pkt_target_mac = '02:03:04:05:06:07' arp = ARP(make_arp_packet( pkt_sender_ip, pkt_sender_mac, pkt_target_ip, pkt_target_mac, op=ARP_OPERATION.REPLY)) self.assertItemsEqual( arp.bindings(), [ (IPAddress(pkt_sender_ip), EUI(pkt_sender_mac)), (IPAddress(pkt_target_ip), EUI(pkt_target_mac)) ])
def _getEUI(ipAddress, mac=""): """ Returns EUI from IPAddress """ if not isinstance(ipAddress, IPAddress): raise ValueError("Expected ipAddress to be of type netaddr.IPAddress") if mac == "": mac = _getMAC(ipAddress) # mac is None if testing on localhost if mac is None: return mac eui = EUI(mac) eui.dialect = mac_unix eui.dialect.word_fmt = "%.2X" return eui
def validate_host(self, value): if value and not isinstance(value, Host): try: value = EUI(value, dialect=mac_unix_common) host = Host.objects.filter(pk=value).first() except (AddrFormatError, TypeError): host = Host.objects.filter(hostname=value.lower()).first() if not host: raise serializers.ValidationError( "The hostname enetered does not exist. Please first create the host." ) return host return None
def get_cm_mac_cmts_format(self, mac): """to convert mac adress to the format that to be used on cmts :param mac: mac address of CM in foramt XX:XX:XX:XX:XX:XX or XX-XX-XX-XX-XX-XX :type mac: string :return: the cm_mac in cmts format xxxx.xxxx.xxxx (lowercase) :rtype: string """ if mac is None: return None mac = EUI(mac) mac.dialect = mac_cisco return str(mac)
def encode(port_list): mac_address = 0 mac = EUI(mac_address) mac[0] = 0x91 assert len(port_list) < 5 for idx, value in enumerate(port_list): mac[idx + 1] = value mac.dialect = mac_unix_expanded key = str(mac) return key
def generate(wifi): interface = wifi['intf'] # always stop hostapd service first before reconfiguring it call(f'systemctl stop hostapd@{interface}.service') # always stop wpa_supplicant service first before reconfiguring it call(f'systemctl stop wpa_supplicant@{interface}.service') # Delete config files if interface is removed if wifi['deleted']: if os.path.isfile(hostapd_conf.format(**wifi)): os.unlink(hostapd_conf.format(**wifi)) if os.path.isfile(wpa_suppl_conf.format(**wifi)): os.unlink(wpa_suppl_conf.format(**wifi)) return None if not wifi['mac']: # http://wiki.stocksy.co.uk/wiki/Multiple_SSIDs_with_hostapd # generate locally administered MAC address from used phy interface with open('/sys/class/ieee80211/{}/addresses'.format(wifi['phy']), 'r') as f: # some PHYs tend to have multiple interfaces and thus supply multiple MAC # addresses - we only need the first one for our calculation tmp = f.readline().rstrip() tmp = EUI(tmp).value # mask last nibble from the MAC address tmp &= 0xfffffffffff0 # set locally administered bit in MAC address tmp |= 0x020000000000 # we now need to add an offset to our MAC address indicating this # subinterfaces index tmp += int(findall(r'\d+', interface)[0]) # convert integer to "real" MAC address representation mac = EUI(hex(tmp).split('x')[-1]) # change dialect to use : as delimiter instead of - mac.dialect = mac_unix_expanded wifi['mac'] = str(mac) # render appropriate new config files depending on access-point or station mode if wifi['op_mode'] == 'ap': render(hostapd_conf.format(**wifi), 'wifi/hostapd.conf.tmpl', wifi) elif wifi['op_mode'] == 'station': render(wpa_suppl_conf.format(**wifi), 'wifi/wpa_supplicant.conf.tmpl', wifi) return None
def test_eui64_dialects(): mac = EUI('00-1B-77-49-54-FD-12-34') assert str(mac) == '00-1B-77-49-54-FD-12-34' mac = EUI('00-1B-77-49-54-FD-12-34', dialect=eui64_unix) assert str(mac) == '0:1b:77:49:54:fd:12:34' mac = EUI('00-1B-77-49-54-FD-12-34', dialect=eui64_unix_expanded) assert str(mac) == '00:1b:77:49:54:fd:12:34' mac = EUI('00-1B-77-49-54-FD-12-34', dialect=eui64_cisco) assert str(mac) == '001b.7749.54fd.1234' mac = EUI('00-1B-77-49-54-FD-12-34', dialect=eui64_bare) assert str(mac) == '001B774954FD1234'
def get_ertr_ipv4(self, mac): '''Getting erouter ipv4 from CMTS ''' self.sendline("show cable modem %s cpe" % mac) self.expect(self.prompt) from netaddr import EUI import netaddr mac = EUI(mac) ertr_mac = EUI(int(mac) + 2) ertr_mac.dialect = netaddr.mac_cisco ertr_ipv4 = re.search('(%s) .* (%s)' % (ValidIpv4AddressRegex, ertr_mac), self.before) if ertr_ipv4: ipv4 = ertr_ipv4.group(1) return ipv4 else: return None
def to_python(self, value): if value is None: return value try: return EUI(value, version=64, dialect=eui64_unix_expanded_uppercase) except AddrFormatError: raise ValidationError(f"Invalid WWN format: {value}")
def main(): """ Main Function, execution starts here. """ nornir = InitNornir(config_file="config.yaml") target = EUI(input("Enter the MAC address you wish to find: ")) nornir.run(task=get_interface_info, target=target)
def __init__(self, value): if isinstance(value, EUI): # If MAC adress is already an EUI class, turns it into an integer self.value = int(value) else: # Otherwise store it directly self.value = int(EUI(value))
def test__refreshed_binding(self): bindings = {} ip = IPAddress("192.168.0.1") mac = EUI("00:01:02:03:04:05") vid = None update_bindings_and_get_event(bindings, vid, ip, mac, 0) event = update_bindings_and_get_event(bindings, vid, ip, mac, SEEN_AGAIN_THRESHOLD) self.assertThat( bindings, Equals({(vid, ip): { "mac": mac, "time": SEEN_AGAIN_THRESHOLD }}), ) self.assertThat( event, Equals( dict( event="REFRESHED", ip=str(ip), mac=format_eui(mac), time=SEEN_AGAIN_THRESHOLD, vid=vid, )), )
def to_internal_value(self, data): if data is None: return data try: return EUI(data, dialect=mac_unix_common) except AddrFormatError: self.fail('invalid')
def mac(raw): """ Converts a raw string to a standardised MAC Address EUI Format. :param raw: the raw string containing the value of the MAC Address :return: a string with the MAC Address in EUI format Example: .. code-block:: python >>> mac('0123.4567.89ab') u'01:23:45:67:89:AB' Some vendors like Cisco return MAC addresses like a9:c5:2e:7b:6: which is not entirely valid (with respect to EUI48 or EUI64 standards). Therefore we need to stuff with trailing zeros Example >>> mac('a9:c5:2e:7b:6:') u'A9:C5:2E:7B:60:00' If Cisco or other obscure vendors use their own standards, will throw an error and we can fix later, however, still works with weird formats like: >>> mac('123.4567.89ab') u'01:23:45:67:89:AB' >>> mac('23.4567.89ab') u'00:23:45:67:89:AB' """ if raw.endswith(":"): flat_raw = raw.replace(":", "") raw = "{flat_raw}{zeros_stuffed}".format(flat_raw=flat_raw, zeros_stuffed="0" * (12 - len(flat_raw))) return str(EUI(raw, dialect=_MACFormat))
def get(self, search, params): """Get the events in machine histories related to the search. Args: search: the IP or MAC address used in the search. params: the dictionary built by the search view. Returns: A list of MachineHistorySearchEvent in reverse chronological order. """ self.start = params.get("s", None) self.end = params.get("e", None) search_type = params.get("t", 0) self.events = [] if search_type == "ip": try: return self._get_by_ip(search)[::-1] except: pass elif search_type == "mac": try: search = EUI(search, dialect=default_dialect()) return self._get_by_mac(search)[::-1] except: pass return []
def retrieve_oui(record): mac = EUI(record.mac) try: org = mac.oui.registration().org except NotRegisteredError: org = None return org
def get_queries_for_device(mac, week, sort=False, limit=None): device_queries = redis.hgetall( _DELIMITER.join((_PREFIX, _DEVICE, _QUERIED, str(EUI(mac)), _WEEK, str(week), _DOMAIN))) blocked = redis.hgetall( _DELIMITER.join( (_PREFIX, _DNSMASQ, _BLOCKED, _WEEK, str(week), _DOMAIN))) blocked_queries = list() queries = list() if sort: device_queries = sorted(device_queries.items(), cmp=lambda x, y: int(x) - int(y), key=operator.itemgetter(1), reverse=True) else: device_queries = device_queries.items() for domain, count in device_queries: if domain in blocked: blocked_queries.append([domain, count]) elif 'upri.box' not in domain: queries.append([domain, count]) if len(blocked_queries) > 0: blocked_queries_num = sum(float(query[1]) for query in blocked_queries) device_queries_num = sum(float(query[1]) for query in device_queries) block_percent = round( blocked_queries_num / (device_queries_num + blocked_queries_num) * 100.00, 2) else: block_percent = 0 return queries[:limit], blocked_queries[:limit], block_percent
def _mac_lookup(self, value): if not value: return '' try: return EUI(value).oui.registration().org except NotRegisteredError: return ''
def get_vendor(self, mac_address): from netaddr import EUI try: vendor = EUI(mac_address).oui.registration().org except: vendor = "Unknown" return vendor
def test_distribute_minimal(self): host = Host("paravance-1") machine = MachineConfiguration( roles=["r1"], flavour="tiny", undercloud=[host], number=1 ) machines = [machine] g5k_subnet = {"mac_start": "00:16:3E:9E:44:00", "mac_end": "00:16:3E:9E:47:FE"} vmong5k_roles = _distribute(machines, [g5k_subnet]) self.assertEqual(1, len(vmong5k_roles["r1"])) vm = vmong5k_roles["r1"][0] # we skip the first mac self.assertEqual(EUI(int(EUI(g5k_subnet["mac_start"])) + 1), vm.eui) self.assertEqual(host, vm.pm)
def __init__(self, id=0, name=None, mac_address=None, ip_address=None, inactivity_time=None, rx_packets=None, tx_packets=None, rx_bitrate=None, tx_bitrate=None, signal=None): self.id = id self.name = name self.mac_address = mac_address self.ip_address = ip_address self.inactivity_time = inactivity_time self.rx_packets = rx_packets self.tx_packets = tx_packets self.tx_bitrate = tx_bitrate self.rx_bitrate = rx_bitrate self.signal = signal self.vendor = None try: self.vendor = EUI(mac_address).oui.registration( ).org # OUI - Organizational Unique Identifier except Exception as e: pass
def test_mac_address_properties(): mac = EUI('00-1B-77-49-54-FD') assert repr(mac) == "EUI('00-1B-77-49-54-FD')" assert str(mac) assert str(mac.oui) == '00-1B-77' assert mac.ei == '49-54-FD' assert mac.version == 48
def test__properties(self): pkt_sender_mac = '01:02:03:04:05:06' pkt_sender_ip = '192.168.0.1' pkt_target_ip = '192.168.0.2' pkt_target_mac = '00:00:00:00:00:00' eth_src = '02:03:04:05:06:07' eth_dst = 'ff:ff:ff:ff:ff:ff' arp_packet = make_arp_packet(pkt_sender_ip, pkt_sender_mac, pkt_target_ip, pkt_target_mac) arp = ARP(arp_packet, src_mac=hex_str_to_bytes(eth_src), dst_mac=hex_str_to_bytes(eth_dst)) self.assertThat(arp.source_eui, Equals(EUI(pkt_sender_mac))) self.assertThat(arp.target_eui, Equals(EUI(pkt_target_mac))) self.assertThat(arp.source_ip, Equals(IPAddress(pkt_sender_ip))) self.assertThat(arp.target_ip, Equals(IPAddress(pkt_target_ip)))
def to_python(self, value): if value is None: return value try: return EUI(value, version=48, dialect=mac_unix_expanded_uppercase) except AddrFormatError as e: raise ValidationError(e)
def test_eui_iab(): mac = EUI('00-50-C2-00-0F-01') assert mac.is_iab() iab = mac.iab assert str(iab) == '00-50-C2-00-00-00' assert iab == IAB('00-50-C2-00-00-00') reg_info = iab.registration() assert reg_info.address == [ '1241 Superieor Ave E', 'Cleveland OH 44114', 'US', ] assert reg_info.iab == '00-50-C2-00-00-00' assert reg_info.org == 'T.L.S. Corp.'
def test_eui_dialect_property_assignment(): mac = EUI('00-1B-77-49-54-FD') assert str(mac) == '00-1B-77-49-54-FD' mac.dialect = mac_pgsql assert str(mac) == '001b77:4954fd'
def main(args): parser = argparse.ArgumentParser( description='Find active users on the current wireless network.') parser.add_argument('-p', '--packets', default=1000, type=int, help='How many packets to capture.') parser.add_argument('-i', '--interface', default=None, type=str, help='Which wireless interface to use.') parser.add_argument('-s', '--ssid', default=None, type=str, help='Which SSID to use.') parser.add_argument('-r', '--results', default=None, type=int, help='How many results to show.') args = parser.parse_args() try: if args.interface: iface = args.interface else: wireless = Wireless() ifaces = wireless.interfaces() eprint('Available interfaces: {}'.format(', '.join(ifaces))) iface = ifaces[-1] eprint('Interface: {}'.format(iface)) if args.ssid: ssid = args.ssid else: wireless = Wireless() ssid = wireless.current() if ssid is None: eprint(NO_SSID) return eprint('SSID: {}'.format(ssid)) except: eprint(NO_WIRELESS) raise mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}' mac_re = re.compile(mac_re_str, re.I) network_macs = set() try: gws = netifaces.gateways()[netifaces.AF_INET] gw_ifaces = ', '.join([gw[1] for gw in gws]) eprint('Available gateways: {}'.format(gw_ifaces)) gw_ip = next(gw[0] for gw in gws if gw[1] == iface) eprint('Gateway IP: {}'.format(gw_ip)) gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)]) gw_arp = gw_arp.decode('utf-8') gw_mac = EUI(mac_re.search(gw_arp).group(0)) gw_mac.dialect = mac_unix_expanded network_macs.add(gw_mac) eprint('Gateway MAC: {}'.format(gw_mac)) except StopIteration: eprint('No gateway for {}'.format(iface)) except KeyError: eprint('No gateways available: {}'.format(netifaces.gateways())) except: eprint(NO_GATEWAY_MAC) bssid_re = re.compile(' BSSID:(\S+) ') tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I) length_re = re.compile(' length (\d+)') client_macs = set() data_totals = defaultdict(int) cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split() try: bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}' progress = tqdm(run_process(cmd), total=args.packets, bar_format=bar_format) for line in progress: line = line.decode('utf-8') # find BSSID for SSID if ssid in line: bssid_matches = bssid_re.search(line) if bssid_matches: bssid = bssid_matches.group(1) if 'Broadcast' not in bssid: network_macs.add(EUI(bssid)) # count data packets length_match = length_re.search(line) if length_match: length = int(length_match.group(1)) mac_matches = tcpdump_mac_re.findall(line) if mac_matches: macs = set([EUI(match[1]) for match in mac_matches]) leftover = macs - network_macs if len(leftover) < len(macs): for mac in leftover: data_totals[mac] += length client_macs.add(mac) if progress.n < progress.total: eprint('Sniffing finished early.') except subprocess.CalledProcessError: eprint('Error collecting packets.') raise except KeyboardInterrupt: pass totals_sorted = sorted(data_totals.items(), key=lambda x: x[1], reverse=True) eprint('Total of {} user(s)'.format(len(totals_sorted))) for mac, total in reversed(totals_sorted[:args.results]): mac.dialect = mac_unix_expanded if total > 0: print('{}\t{} bytes'.format(mac, total))
def mk_mac(i): mac = EUI(i) mac.dialect = mac_unix return str(mac)
hvnum = int (sys.argv[1]) vmnum = int (sys.argv[2]) username = sys.argv[3] password = sys.argv[4] except : print "%s [HVNUM] [VMNUM] [username] [password]" % sys.argv[0] sys.exit (1) intf = "shownet-mgmt" macaddr = "02:00:aa:01:%02d:%02d" % (hvnum, vmnum) config = "running-config-%d-%d.xml" % (hvnum, vmnum) controller = "172.16.30.10" mac = EUI (macaddr) mgmtaddr = mac.ipv6_link_local () p = pexpect.spawn ("telnet %s%%%s" % (mgmtaddr, intf)) p.logfile_read = sys.stdout p.expect (r'login: '******'Password: '******'grandslam@pa-vm> ') p.send ("set cli pager off\n")
def test_mac_to_ipv6_link_local(): mac = EUI('00-0F-1F-12-E7-33') ip = mac.ipv6_link_local() assert ip == IPAddress('fe80::20f:1fff:fe12:e733') assert ip.is_link_local() assert mac.eui64() == EUI('00-0F-1F-FF-FE-12-E7-33')
def test_eui64(): eui = EUI('00-1B-77-FF-FE-49-54-FD') assert eui == EUI('00-1B-77-FF-FE-49-54-FD') assert eui.oui == OUI('00-1B-77') assert eui.ei == 'FF-FE-49-54-FD' assert eui.eui64() == EUI('00-1B-77-FF-FE-49-54-FD')
def test_mac_address_numerical_operations(): mac = EUI('00-1B-77-49-54-FD') assert int(mac) == 117965411581 assert hex(mac) == '0x1b774954fd' assert mac.bits() == '00000000-00011011-01110111-01001001-01010100-11111101' assert mac.bin == '0b1101101110111010010010101010011111101'
def test_eui64_dialect_property_assignment(): mac = EUI('00-1B-77-49-54-FD-12-34') assert str(mac) == '00-1B-77-49-54-FD-12-34' mac.dialect = eui64_cisco assert str(mac) == '001b.7749.54fd.1234'
parser.add_option('-t', "--telnet", action="store_true", default=False, dest="telnet", help="Use telnet for connections") (options, args) = parser.parse_args() if not options.mac: print "MAC address required as argument to execute mactrace" parser.print_help() sys.exit(0) def die(msg): print msg sys.exit(1) MAC = EUI(options.mac) MAC.dialect = netaddr.mac_cisco start = 1 print "Search MAC: %s" % MAC next_switch_ip = options.next_switch_ip if not next_switch_ip or next_switch_ip == "": import json hostname = json.loads(clid("show hostname")) hostname = hostname["hostname"] out = json.loads(clid("show mac address-table address %s" % options.mac)) learnedmacport = out['TABLE_mac_address']['ROW_mac_address']["disp_port"] print "%d %s %s" % (start, hostname, learnedmacport) start += 1 mac_count = int(cli("show mac address-table interface %s | count" % learnedmacport)[1])
#print e return False except DataError, e: print e print device_info.identity print device_info.mac_address for line in sys.stdin: lines = line.split() if len(lines) == 5 and 'Identity' in line: mac_username_dict[previous_line_mac[-17:]] = lines[4] for a in lines: if 'SA' in a: previous_line_mac = a for mac, identity in mac_username_dict.items(): device_info = DeviceInfo( identity = identity, mac_address = mac, ) a = save_device_info(device_info) if a: try: oui = EUI(mac).oui print mac, ' | ', oui.registration().org.ljust(31), ' | ', identity.ljust(30), ' | ', a except: pass