def send_dev_updates(): while True: logger.info("Updating all devices") # report all monitored devices lat_arp_table = get_arp_table() logger.info(monitored_mac) for device in monitored_mac: # report status of devices in monitor list logger.info("Updating device {}".format(device)) dev_arp = next( (item for item in lat_arp_table if item["HW address"] == device), None) # check if device in arp table logger.info("device {} in arptable has flag {}".format( device, "NF" if dev_arp is None else dev_arp["Flags"])) if dev_arp is not None: try: update_hass_state( device, "connected" if dev_arp["Flags"] == "0x2" else "not_connected" ) # report home only if dev in arp and flag is 2 except Exception as exc: logger.error(traceback.print_exc()) time.sleep(30)
def get_ip_addr(hw_addr): os.system("fping -a -r 0 -g 172.31.105.0/22 -q | fping") for addr in python_arptable.get_arp_table(): if addr['HW address'] == hw_addr: print("IP of " + hw_addr + " is " + addr['IP address']) return addr['IP address'] return None
def get_arp_hosts(self): """ Return list of arp hosts from arp cache """ for arp in get_arp_table(): if arp.get('IP address'): self.arp_hosts.append(arp.get('IP address'))
def main(): global cache interface = 'eth0' argv = sys.argv l = get_if_list() if len(l) == 0: exit(0) if len(argv) != 1 and len(argv) != 3: exit(0) if len(argv) == 1: if interface in l: pass else: interface = l[0] if len(argv) == 3: if argv[1] == '-i': interface = argv[2] if l.index(interface) == -1: exit(0) if argv[1] != '-i': exit(0) # Used the following link to get the arp table # https://pypi.org/project/python_arptable/ arp_table = get_arp_table() interface_dict = dict() for arp in arp_table: if l.index(arp['Device']) != -1: temp = dict({arp['IP address']:arp['HW address']}) interface_dict.setdefault(arp['Device'], temp) cache = interface_dict[interface] sniff(iface=interface, filter='arp', prn=arp_checker, stop_filter=nonstop)
def showip(request): HWaddress = "" arptable = get_arp_table() for row in arptable: if row['IP address'] == request.META['REMOTE_ADDR']: HWaddress = row['HW address'] break return HttpResponse("your Hardware address is %s;" % (HWaddress))
def get_ip_addrs_for_mac(mac_addrs): """ Gets IP addresses from MAC addresses using ARP table. """ addrs = [] for ma in mac_addrs: for entry in get_arp_table(): if entry['HW address'] == ma: addrs.append(entry['IP address']) return addrs
def learn_mac_addresses(): arp_table_list = get_arp_table() arp_table = dict() for arp_entry in arp_table_list: if arp_entry["HW address"] != "00:00:00:00:00:00": arp_table[arp_entry["IP address"]] = arp_entry["HW address"] pprint(arp_table) return arp_table
def get_dg_mac(gateway_ip): ##Import the contents of the ARP table for reading arp_table = get_arp_table() ##Loop through each ARP entry to check whether the gateway address is present for arp_entry in arp_table: if arp_entry["IP address"] == gateway_ip: ##Grab the MAC address associated with the gateway address gateway_mac = arp_entry["HW address"] return gateway_mac
def get_arp_linux(self): data = arp_table.get_arp_table() x = groupby(data, lambda x: x['Device']) processed = [{ "name": interface[0], "entries": [{ key[1]: entry[key[0]] for key in [("IP address", "ip"), ("HW address", "mac")] } for entry in interface[1]] } for interface in x] return processed
def calculaMAC(ip): os.system("ping -c 2 " + ip) ##Import the contents of the ARP table for reading arp_table = get_arp_table() gateway_mac = '00:00:00:00:00:00' ##Loop through each ARP entry to check whether the gateway address is present for arp_entry in arp_table: if arp_entry['IP address'] == str(ip): ##Grab the MAC address associated with the gateway address gateway_mac = str(arp_entry['HW address']) print gateway_mac break; return gateway_mac
def check_arp_table(): """ option 2 for detect a ARP Spoof attack we sending each row an ping request with the arp table data """ arp_table = get_arp_table() for i, row in enumerate(arp_table): ip = row['IP address'] mac = row['HW address'] ans = srp1(Ether(src=get_if_hwaddr(row['Device']), dst=mac) / IP(dst=ip) / ICMP(), timeout=5, verbose=False) if ans is None and (ip, mac) not in option2_suspicious_lst: option2_suspicious_lst.append((ip, mac))
def get_dg_mac(): ##Grab the default gateway address gws = netifaces.gateways() gateway_address_list = gws['default'][netifaces.AF_INET] gateway_address = gateway_address_list[0] ##Import the contents of the ARP table for reading arp_table = get_arp_table() ##Loop through each ARP entry to check whether the gateway address is present for arp_entry in arp_table: if arp_entry["IP address"] == gateway_address: ##Grab the MAC address associated with the gateway address gateway_mac = arp_entry["HW address"] return gateway_mac
def update_from_cache(self, iface_): iface_info = get_iface_info(iface_) current_arp_table = get_arp_table() for entry in current_arp_table: # print(entry["IP address"],entry["HW address"]) # validation if not entry["Device"] == iface_: continue if validate_entry(iface_info, entry): self.update_entry(entry["IP address"], entry["HW address"]) # add entry to whitelist add_static_entry(entry) # add entry to arp-cache else: add_to_blacklist(entry) if self.ip_is_exist(entry["IP address"]): self.delete_entry(entry) # delete entry from whitelist delete_entry(entry) # delete entry from arp-cache self.write2file()
def learn_mac_addresses(): try: if get_arp_table: arp_table_list = get_arp_table() else: return {} except FileNotFoundError as e: return {} arp_table = dict() for arp_entry in arp_table_list: if arp_entry["HW address"] != "00:00:00:00:00:00": arp_table[arp_entry["IP address"]] = arp_entry["HW address"] pprint(arp_table) return arp_table
def _tasmota_discovery(): # try to connect assuming is a tasmota device L.l.info("Begin tasmota network scan") net_hosts = utils.get_my_network_ip_list() for ip in net_hosts: try: # L.l.info("Tasmota discovery IP {}".format(ip)) dev_name = utils.parse_http(url="http://{}/cm?cmnd=friendlyname1".format(ip), start_key='{"FriendlyName1":"', end_key='"}', timeout=3, silent=True) if dev_name is not None: arp = python_arptable.get_arp_table() for entry in arp: if IPv4Address(entry["IP address"]) == ip: mac = entry["HW address"] if mac in P.mac_list: config_file = P.mac_list[mac] file_name = os.path.basename(config_file) # dev_name = utils.parse_http(url="http://{}/cm?cmnd=friendlyname1".format(ip), # start_key='{"FriendlyName1":"', end_key='"}') mqtt_topic = utils.parse_http(url="http://{}/cm?cmnd=Topic".format(ip), start_key='{"Topic":"', end_key='"}', timeout=3) last_update = utils.parse_http(url="http://{}/cm?cmnd=friendlyname2".format(ip), start_key='{"FriendlyName2":"', end_key='"}', timeout=3) if dev_name != file_name or mqtt_topic != file_name \ or last_update != str(utils.get_base_location_now_date().day): # tasmota device is not configured L.l.info("Configuring tasmota device {} as {}".format(ip, file_name)) _tasmota_config(config_file=P.TASMOTA_CONFIG, device_name=file_name, ip=ip) _tasmota_config(config_file=config_file, device_name=file_name, ip=ip) mqtt_topic = utils.parse_http(url="http://{}/cm?cmnd=Topic".format(ip), start_key='{"Topic":"', end_key='"}', timeout=3) if mqtt_topic != file_name: L.l.error("Failed to set mqtt topic {}, actual={}".format(file_name, mqtt_topic)) else: L.l.warning("Found tasmota device {} {} without config file".format(dev_name, ip)) break else: L.l.info("Tasmota scan: IP {} not responding".format(ip)) except Exception as ex: L.l.info("Tasmota scan: IP {} failed".format(ip)) pass L.l.info("Finalised tasmota network scan")
def update_from_cache(self, iface_): iface_info = get_iface_info(iface_) current_arp_table = get_arp_table() for entry in current_arp_table: # validation if not entry["Device"] == iface_: continue if arp.validate_entry(iface_info, entry): print("Verify entry: {} {}".format(entry["HW address"], entry["IP address"])) self.update_entry(entry["IP address"], entry["HW address"]) arp.add_static_entry(entry) # add entry to arp-cache print('\n') else: print("Verify entry failed: {} {}".format(entry["HW address"], entry["IP address"])) if self.ip_is_exist(entry["IP address"]): print("Delete entry from whitelist") self.delete_entry(entry) print("Delete entry from arp cache") arp.delete_entry(entry) print("\n") self.write2file()
def update_data(self): self.arp_dest_map = {} self.arp_dest_list = [] for entry in python_arptable.get_arp_table(): dev = entry['Device'] mac = entry['HW address'] ip = entry['IP address'] if_index = mibs.get_index_from_str(dev) if if_index is None: continue mactuple = mac_decimals(mac) machex = ''.join(chr(b) for b in mactuple) # if MAC is all zero #if not any(mac): continue iptuple = ip2tuple_v4(ip) subid = (if_index, ) + iptuple self.arp_dest_map[subid] = machex self.arp_dest_list.append(subid) self.arp_dest_list.sort()
def update_data(self): self.arp_dest_map = {} self.arp_dest_list = [] for entry in python_arptable.get_arp_table(): dev = entry['Device'] mac = entry['HW address'] ip = entry['IP address'] if_index = mibs.get_index_from_str(dev) if if_index is None: continue mactuple = mac_decimals(mac) machex = ''.join(chr(b) for b in mactuple) # if MAC is all zero #if not any(mac): continue iptuple = ip2tuple_v4(ip) subid = (if_index,) + iptuple self.arp_dest_map[subid] = machex self.arp_dest_list.append(subid) self.arp_dest_list.sort()
def start_Sniping(): global a, arp_attack capture = pyshark.LiveCapture(interface="eth0") """ capture.set_debug() """ i = 0 while(1): packet = pyshark.LiveCapture(interface= "eth0" ) for cap in packet.sniff_continuously(packet_count=1): data = [] if (i == 0) : pack_time = 0 time = float(cap.sniff_timestamp) i = 1 pack_time = float(cap.sniff_timestamp) - time time = float(cap.sniff_timestamp) size = cap.length packet = 1 prot = cap.transport_layer if hasattr(cap, 'tcp'): port = cap.tcp.dstport if hasattr(cap, 'udp'): port = cap.udp.dstport print (pack_time, "\t", size, "\t", packet, "\t", prot, "\t", port) data.append(pack_time) data.append(packet) data.append(prot) data.append(port) start_Detection(data) b = np.array([[randint(1,30)], [randint(1,30)],[randint(1,30)],[randint(1,30)], [randint(1,30)],[randint(1,30)]]) a = np.append(a, b, axis = 1) arp_tab = arp.get_arp_table() b,c = [],[] for i in range(len(arp_tab)): b.append(arp_tab[i]["IP address"]) c.append(arp_tab[i]["HW address"]) if(len(set(b))>len(set(c))): arp_attack = True
username=username, password=password, port=port) def exec_cmd(self, cmd): stdin, stdout, stderr = self.ssh.exec_command(cmd) if stderr.channel.recv_exit_status() != 0: return stderr else: return stdout #iface = input("Digite sua interface de rede: ") #ip = ni.ifaddresses(iface) ip = ni.ifaddresses('wlp3s0') arp = get_arp_table() G = nx.Graph() atributos = {0: {'IP': ip[2][0]['addr'], 'MAC': ip[17][0]['addr']}} G.add_node(0) for i in range(1, len(arp) + 1): atributos[i] = { 'IP': arp[i - 1]['IP address'], 'MAC': arp[i - 1]['HW address'] } G.add_node(i) lat = os.popen('ping -c 1 ' + arp[i - 1]['IP address']).read() lat = float(lat.split('time=')[1].split('ms')[0]) G.add_weighted_edges_from([(0, i, lat)]) nx.set_node_attributes(G, atributos)
def _update_from_arptable(self): for entry in python_arptable.get_arp_table(): dev = entry['Device'] mac = entry['HW address'] ip = entry['IP address'] self._update_arp_info(dev, mac, ip)
def __init__(self): self._arp_table = {x['IP address']: x['HW address'] for x in python_arptable.get_arp_table()}