예제 #1
0
    def extract_devices(self):
        """
        Extract devices from the captured packets.

        Returns:
            pandas.DataFrame:
                Device parameters extracted from the captured packets.

        """
        devs = pd.DataFrame(
            columns=["MAC", "Vendor", "Times", "Frame Subtypes"])
        if (self.packets.empty):
            return devs
        macs = self.packets["MAC"].unique()
        ML = MacLookup()
        ML.update_vendors()
        for mac in macs:
            frames = self.packets.loc[self.packets["MAC"] == mac]
            if (mac[1] == "2" or mac[1] == "6" or mac[1] == "a"
                    or mac[1] == "e" or mac[1] == "A" or mac[1] == "E"):
                vendor = "Randomized"
            else:
                try:
                    vendor = ML.lookup(mac)
                except KeyError:
                    vendor = "Unknown"
            mins = np.unique(
                np.array([(60 * tm.hour + tm.minute)
                          for tm in frames["Time"]]))
            subtypes = frames["Frame Subtype"].unique()
            devs.loc[len(devs)] = [mac, vendor, mins, subtypes]
        return devs
예제 #2
0
def get_manufacturer(mac):
    search_manufacturer = MacLookup()
    try:
        manufacture = search_manufacturer.lookup(mac)
    except:
        manufacture = "Unknown"
    return manufacture
예제 #3
0
def get_hosts():

    scanner = nmap.PortScanner()
    print("starting scan")
    start = time.time()
    scanner.scan("172.16.80.0/23", "22", arguments="-n")
    print("completed scan", round(time.time() - start, 2))
    addresses = scanner.all_hosts()
    vendor_lookup = MacLookup()

    local_interface_map = get_local_ipv4_interface_map()

    hosts = []

    print("getting mac address of network cards")
    start = time.time()
    for address in addresses:
        mac = get_mac_address(ip=address)

        if not mac and address in local_interface_map:
            mac = get_mac_address(interface=local_interface_map[address])

        try:
            vendor = vendor_lookup.lookup(mac) if mac else None
        except KeyError:
            print("error processing mac for", address)
        hosts.append({"ip": address, "mac": mac, "vendor": vendor})
    print("mac address acquired", round(time.time() - start, 2))
    return hosts
예제 #4
0
def network_device_list(host, token, headers, mac):
    url = "https://" + host + "/dna/intent/api/v1/client-detail?timestamp&macAddress=" + mac
    headers["x-auth-token"] = token
    response = requests.get(url, headers=headers, verify=False)
    #print(response)
    data = response.json()
    #print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ':')))
    #print(json.dumps(data['topology']['nodes'], sort_keys=True, indent=4, separators=(',', ':')))

    try:
        print(mac, data['topology']['nodes'][0]['ip'],
              (MacLookup().lookup(mac)))
    except KeyError:
        print(mac, ' No Data')

    filename = 'H:/CSV_ISE_Stuff/NDOT_IP.csv'
    write_header = not os.path.exists(filename)
    with open(filename, 'a', newline='') as csvfile:
        headers = ['MAC Address', 'IP Address', 'OUI']
        writer = csv.DictWriter(csvfile, fieldnames=headers)
        if write_header:
            writer.writeheader()
        writer = csv.writer(csvfile)
        try:
            csvdata = (mac, data['topology']['nodes'][0]['ip'],
                       (MacLookup().lookup(mac)))
        except KeyError:
            csvdata = (mac, ' No Data')

        writer.writerow(csvdata)
예제 #5
0
def find_mac(mac_addr):
    mac_data = MacLookup()
    mac_data.update_vendors()
    try:
        return mac_data.lookup(mac_addr)
    except KeyError:
        return "Unknown"
class NmapMacScan(NmapBasic):
    def __init__(self, networks, unknown="unknown"):
        super().__init__(networks)
        self.unknown = unknown
        self.mac_search = MacLookup()

    def update_mac(self, ip):
        """
        Update Mac info
        :param ip: IP address (ie: 192.168.1.1)
        :return: True if MAC is found, False otherwise
        """
        mac = getmac.get_mac_address(ip=ip)
        if mac is None:
            return False
        else:
            self.scan_results[ip]["macaddress"] = mac
            return True

    def update_vendor(self, ip):
        """
        Update MAC vendor if Mac is found
        :param ip: IP address (ie: 192.168.1.1)
        :return: None
        """
        logging.debug("Updating MAC table")
        self.mac_search.update_vendors()
        vendor_fetch = self.mac_search.lookup(
            self.scan_results[ip]["macaddress"])
        self.scan_results[ip]["vendor"] = vendor_fetch

    def correct_missing_mac(self, host):
        """
        Correct description if macaddress is not found
        :param host: host key in scan_results
        :return: None
        """
        if not self.scan_results[host]["macaddress"]:
            self.scan_results[host]["description"] = self.unknown
            self.scan_results[host].pop("macaddress")

    def scan(self):
        """
        Scan defined networks and conditionally check for mac vendor
        :return: scan_results = list()
        """
        for host, v in self.scan_results.items():
            if v.get("macaddress") or self.update_mac(host):
                self.update_vendor(ip=host)
            self.correct_missing_mac(host)
        return self.scan_results

    def run(self):
        return self.scan()
예제 #7
0
def create_mac_table(key, lst, lookup=False):
    td = [[key]]
    if lookup:
        td[0].append("vendor")
        m = MacLookup()

    for i in lst:
        try:
            if lookup:
                td.append([i, m.lookup(i)])
            else:
                td.append([i])
        except Exception:
            td.append([i, ""])
    return td
예제 #8
0
def choose_target():
    subprocess.call("clear", shell=True)
    print("------------" + Fore.YELLOW + " Choose a Target " + Fore.WHITE +
          "------------")
    global results
    for x in range(len(results)):
        try:
            vendor = MacLookup().lookup(results[x]["mac"])
        except:
            vendor = "UNKNOWN"
        print(
            str(x) + ") " + results[x]["ip"] + "  \t[" + results[x]["mac"] +
            "]  \t[" + vendor + "]")
    try:
        choice = input("\nChoose Target: ")
    except KeyboardInterrupt:
        print(Fore.CYAN + "\n[+]" + Fore.WHITE + " Stopping...")
        subprocess.call("echo 0 > /proc/sys/net/ipv4/ip_forward", shell=True)
        exit(0)
    try:
        int(choice)
    except:
        print(Fore.RED + "[+]" + Fore.WHITE + " Error: Invalid Input!")
        subprocess.call("echo 0 > /proc/sys/net/ipv4/ip_forward", shell=True)
        exit(0)
    if int(choice) in range(len(results)):
        return results[int(choice)]
    else:
        print(Fore.RED + "[+]" + Fore.WHITE + " Error: Choice Invalid!")
        subprocess.call("echo 0 > /proc/sys/net/ipv4/ip_forward", shell=True)
        exit(0)
    def store_device_info(self, device_info):
        """Gather and store the FQDN and vendor-name to make a dictionary for each device containing that information."""
        if (self.os == "Windows" and device_info[-1] == "static"):
            self.static_addrs.append(device_info)

        if (self.os != "Windows"):
            # removing the name for Mac/Linux to normalize the list across OS's
            self.device_info.remove(device_info[0])
            self.device_info[0] = device_info[0].replace('(', '')
            self.device_info[0] = device_info[0].replace(')', '')

        mac_addr = self.fix_mac_addr(device_info[1])

        ip = device_info[0]
        self.name = socket.getfqdn(ip)

        if (self.name == ip):
            self.name = "Unknown_" + str(self.idx)
            self.idx += 1
        else:
            pass

        try:
            self.mac_name = MacLookup().lookup(mac_addr)
        except:
            pass

        self.device_dict[self.name] = device_info
예제 #10
0
def scanNetwork(network):
    user_ip = network
    network = network + "/24"
    network_list = []
    global found_hosts
    nm = nmap.PortScanner()
    a = nm.scan(hosts=network, arguments='-sn')

    with open('../scanlog.txt', 'w') as file:
        file.write(json.dumps(json.loads(json.dumps(a)), indent=4))

    for k, v in a['scan'].items():
        if str(v['status']['state']) == 'up':
            ip4 = str(v['addresses']['ipv4'])
            hostname = str(v['hostnames'][0]['name'])
            mac_addr = get_mac_address(ip=ip4)
            if not hostname:
                hostname = "No hostname found"
            if not mac_addr and ip4 == user_ip:
                mac_addr = get_mac_address()
            if mac_addr:
                try:
                    vendor_name = MacLookup().lookup(mac_addr)
                except KeyError:
                    vendor_name = 'No vendor found'
            else:
                mac_addr = 'Your Interface'
                vendor_name = 'Your Interface'
            if ip4 == user_ip:
                vendor_name += "  (Your Interface)"
            network_list.append([ip4, mac_addr, hostname, vendor_name])
            found_hosts.append([ip4, hostname])
    return network_list
예제 #11
0
def translatetoconfig(confline):
    """Parse an ISC DHCP reservation, and return ISC config format with
    reservation as an IPv4 address"""

    if confline.lstrip().startswith('host'):
        # Translate this line
        try:
            if confformat.match(confline):
                spaces, hostname, reservation, mac = confformat.findall(
                    confline)[0]
                mac_vendor = '"' + MacLookup().lookup(mac) + '"'
            else:
                return ('ERROR')
        except ValueError:
            hostname, reservation, mac = 'LINEERROR', 'LINEERROR', 'LINEERROR'
        except IndexError:
            hostname, reservation, mac = 'LINEERROR', 'LINEERROR', 'LINEERROR'
        if ipformat.match(reservation):
            ipaddress = reservation
        else:
            try:
                ipaddress = gethostbyname(reservation)
            except Exception:
                ipaddress = '0.0.0.0'
        return(spaces + 'host ' + hostname + ' {fixed-address ' + ipaddress + \
                '; hardware ethernet ' + mac + ';}')
        #return([ipaddress, mac, mac_vendor, hostname, reservation, confline])
        #return(','.join([ipaddress, mac, hostname, reservation, confline]))
    else:
        # Return this line unmodified (it's not a DHCP reservation)
        return (confline)
예제 #12
0
class MacAddresses:
    def __init__(self):
        self.__mac_lookup = MacLookup()
        self.__mac_lookup.load_vendors()
        self.__mac_addresses = self.__fetch_mac_addresses()

    def __call__(self):
        return self.__mac_addresses

    # MACアドレスの取得
    def __fetch_mac_addresses(self):
        mac_addresses = {}
        for name, interface in ifcfg.interfaces().items():
            address = interface['ether']
            mac_addresses[name] = {
                'address':
                address,
                'vendor':
                self.__lookup_org_by_mac_address(address)
                if address is not None else None,
            }
        return mac_addresses

    # MACアドレスからベンダを照会する
    # mac_vendor_lookupが存在しないMACアドレスを投げると例外吐いて死にやがるのでこういう邪悪なコードになりました
    def __lookup_org_by_mac_address(self, mac_address):
        oui = MacAddresses.translate_oui(mac_address)
        return self.__mac_lookup.lookup(
            mac_address
        ) if oui in self.__mac_lookup.async_lookup.prefixes else None

    # MACアドレスからOUIを抽出して返す
    @staticmethod
    def translate_oui(mac_address):
        oui = mac_address.replace(':', '').replace('-', '').upper()
        try:
            int(oui, 16)
        except ValueError:
            raise InvalidMacAddressException(
                '{} contains unexpected character'.format(mac_address))
        if len(oui) > 12:
            raise InvalidMacAddressException(
                '{} is not a valid MAC address (too long)'.format(mac_address))
        if type(oui) == str:
            oui = oui.encode('utf8')
        return oui[:6]
예제 #13
0
def get_mac_vendor(mac):
    try:
        #create an instance of an object to search for the vendor
        mac_vendor = MacLookup().lookup(mac)
        #return the vendor mac address
    except:
        mac_vendor = "Unknown Vendor"
    return mac_vendor
예제 #14
0
def render_mac_address(mac):
    mac_parts = re.findall('..', mac)
    mac_address = ":".join(mac_parts).upper()
    mac_address_vendor = MacLookup().lookup(mac_address)
    write_log_line("[{}] MAC Address: {}, MAC Address Vendor: {}".format(
        request.remote_addr, mac_address, mac_address_vendor))
    return render_template("mac_address.html",
                           mac_address=mac_address,
                           mac_address_vendor=mac_address_vendor)
예제 #15
0
 def __init__(self, ip, mac, hostname):
     self._ip = ip
     self._mac = mac
     self._hostname = hostname
     try:
         self._vendor = "UNKNOWN" if mac == "00:00:00:00:00:00" else MacLookup(
         ).lookup(self._mac)
     except:
         self._vendor = "UNKNOWN"
     logging.info("New host created [IP: {}, MAC: {}, Vendor: {}]".format(
         self._ip, self._mac, self._vendor))
     self._services = []
예제 #16
0
def IpScanNetwork(Ini, End, speed):
    if speed == "fast":
        Speed = 0.3
    elif speed == "low":
        Speed = 4
    r = {}
    with open('return/Ips.json', 'w') as json_file:
        json.dump(r, json_file, indent=4)

    with open('return/Ips.json') as f:
        fre = json.load(f)

    inicial = IPv4Address(Ini)
    final = IPv4Address(End)
    o = 0
    ips = [str(IPv4Address(ip)) for ip in range(int(inicial), int(final))]
    try:
        for ip in ips:
            t = ping(ip, timeout=Speed)
            status = False if t is None else True

            if status:
                o = o + 1
                print(f'IP: {ip} [{status}]')
                try:
                    eth_mac = get_mac_address(interface="eth0")
                    win_mac = get_mac_address(interface="Ethernet 3")
                    ip_mac = get_mac_address(ip=ip)
                    ip6_mac = get_mac_address(ip6="::1")
                    host_mac = get_mac_address(hostname="localhost")
                    updated_mac = get_mac_address(ip="10.0.0.1",
                                                  network_request=True)
                    getmac.PORT = 44444
                    mac = getmac.get_mac_address(ip=ip, network_request=True)
                    fabri = MacLookup().lookup(mac)
                    result = {
                        "Ip": ip,
                        "Status": status,
                        "mac": mac,
                        "fabri": fabri
                    }

                    fre[f"Scan{o}"] = result
                except AttributeError:
                    print('Cod: 703')

                    return "Network Erro 02 703"

        with open('return/ips.json', 'w') as json_file:
            json.dump(fre, json_file, indent=4)
            json_file.close()
    except PermissionError:
        print('Cod: 359')
예제 #17
0
def scan(ip):
    arpRequest = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arpRequestBroadcast = broadcast / arpRequest
    answered = scapy.srp(arpRequestBroadcast, timeout=1, verbose=False)[0]

    print(
        "IP\t\t\tMAC Address\t\t\tVendor\n-----------------------------------------------------------"
    )
    for el in answered:
        print(el[1].psrc + "\t\t" + el[1].hwsrc + "\t\t" +
              MacLookup().lookup(el[1].hwsrc))
예제 #18
0
class maclookup():
    def __init__(self):
        self.async_mac = AsyncMacLookup()
        self.mac = MacLookup()

    def UpdateVendorList(self):
        print("Updating MAC address vendor list")
        self.mac.update_vendors()
        print("MAC address vendor list has been updated")

    def lookup(self, addr):
        try:
            loop = asyncio.get_event_loop()
            vendor = loop.run_until_complete(self._lookup(addr))
            return vendor
        except Exception as e:
            print(e)
            print(addr)

    async def _lookup(self, mac_addr):
        return await self.async_mac.lookup(mac_addr)
예제 #19
0
def network_device_list(host, token, headers, mac):
    url = "https://" + host + "/dna/intent/api/v1/client-detail?timestamp&macAddress=" + mac
    headers["x-auth-token"] = token
    response = requests.get(url, headers=headers, verify=False)
    #print(response)
    data = response.json()
    #print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ':')))
    #print(json.dumps(data['topology']['nodes'], sort_keys=True, indent=4, separators=(',', ':')))

    try:
        #print (mac,' IP of Device ',data['detail']['hostIpV4'],' Switch Name ',data['detail']['clientConnection'],' port ',data['detail']['port'])
        print(mac, data['topology']['nodes'][0]['ip'],
              (MacLookup().lookup(mac)), 'Switch',
              data['detail']['clientConnection'], 'Switch IP',
              data['topology']['nodes'][1]['ip'], 'Port',
              data['detail']['port'])
    except KeyError:
        print(mac, 'No Data')

    filename = 'H:/Scripts/DNA/' + name + '.csv'
    write_header = not os.path.exists(filename)
    with open(filename, 'a') as csvfile:
        headers = [
            'MAC Address', 'IP Address', 'OUI', 'Device Name', 'Switch IP',
            'Port ID'
        ]
        writer = csv.DictWriter(csvfile, fieldnames=headers)
        if write_header:
            writer.writeheader()
        writer = csv.writer(csvfile)
        try:
            csvdata = (mac, data['topology']['nodes'][0]['ip'],
                       (MacLookup().lookup(mac)),
                       data['detail']['clientConnection'],
                       data['topology']['nodes'][1]['ip'],
                       data['detail']['port'])
        except KeyError:
            csvdata = (mac, 'No Data')
        writer.writerow(csvdata)
예제 #20
0
def scan(ip):
    request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    broadcast_request = broadcast / request
    ans_ls, unans_ls = scapy.srp(broadcast_request, timeout=1, verbose=False)
    ip_mac_list = []
    for answer in ans_ls:
        ip_mac_dict = {
            "ip": answer[1].psrc,
            "mac": answer[1].hwsrc,
            "vendor": MacLookup().lookup(str(answer[1].hwsrc))
        }
        ip_mac_list.append(ip_mac_dict)
    return ip_mac_list
예제 #21
0
def displayInterfaceInfo(interface_name):
    print(color("\n" + "-" * 30, Colors.green))
    print(
        color("Interface: ", Colors.green) + color(interface_name, Colors.red))
    print(
        color("IP-Address: ", Colors.green) +
        color(get_ip_address(interface_name), Colors.red))
    print(
        color("MAC-Address: ", Colors.green) +
        color(get_mac_address(interface_name), Colors.red))
    print(
        color("Vendor: ", Colors.green) + color(
            (MacLookup().lookup(get_mac_address(interface_name))), Colors.red))
    print(color("-" * 30, Colors.green))
def network_device_list(host, token, headers, mac):
    url = "https://" + host + "/dna/intent/api/v1/client-detail?timestamp&macAddress=" + mac
    headers["x-auth-token"] = token
    response = requests.get(url, headers=headers, verify=False)
    #print(response)
    data = response.json()
    #print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ':')))
    #print(json.dumps(data['topology']['nodes'], sort_keys=True, indent=4, separators=(',', ':')))

    try:
        #print (mac,' IP of Device ',data['detail']['hostIpV4'],' Switch Name ',data['detail']['clientConnection'],' port ',data['detail']['port'])
        print(mac, data['detail']['hostIpV4'], (MacLookup().lookup(mac)))
    except KeyError:
        print(mac, ' Not_in_DNA-C')
예제 #23
0
    def _network_widget(self, profile: str) -> Markup:
        table_data: list = list()
        # noinspection PyPep8Naming
        WIDGET = "network"
        user_profile = _get_profile(profile, WIDGET)
        card_classes = [
            _widget_visible(user_profile.widgets.network.display_widget)
        ]
        self.widget_visibility.update(
            {"network": user_profile.widgets.network.display_widget})
        network_data_list = self.get_network()["data_list"]

        for interface_data in network_data_list:
            ip: IPv4Interface = ipaddress.ip_interface(
                f"{interface_data['ipv4']}/{interface_data['netmask']}")
            try:
                vendor = MacLookup().lookup(interface_data["mac address"])
            except (KeyError, InvalidMacError):
                vendor = None

            if interface_data["ipv4"] != "127.0.0.1" and interface_data["ipv4"] \
                    and not ip.is_link_local and vendor:
                for key, value in interface_data.items():
                    display_name = key.title()
                    display_value = None
                    if "dns" in key.lower():
                        display_name = key.lower().replace("dns", "DNS")
                    elif "dhcp" in key.lower():
                        display_name = key.lower().replace("dhcp", "DHCP")
                    elif "mac" in key.lower():
                        display_name = key.title().replace("Mac", "MAC")
                    elif "state" in key.lower():
                        display_value = _interface_state(value)
                    elif "speed" in key.lower():
                        display_value = _interface_speed(value)
                    elif key.lower().startswith("ip"):
                        display_name = key.lower().replace("ip", "IP")
                        if "ipv4" in key.lower():
                            display_value = ip.with_prefixlen

                    row_content = self._table_row_head % {"head_class": "", "head_content": display_name} + \
                        self._table_data % {"cell_class": "", "cell_content": display_value or value}
                    table_data.append(
                        self._generate_table_row(
                            key, user_profile.widgets.network.display_fields,
                            row_content))

        return self._generate_std_widget(WIDGET.title(), table_data,
                                         card_classes)
예제 #24
0
    def netScan(self, port):
        open = []
        tcpPorts = []
        udpPorts = []
        mac = []
        macVendor = []
        ipAddr = []
        deviceScanner = Discover()
        print("=================================")
        print("Scanning local network and ports")
        print("=================================")
        print("Host IP: " + str(self.hostIP))
        ipRange = self.ipBase + "/16"
        print("[+] IP RANGE [" + str(ipRange) + "]")
        print("++++++++++++++++++++++++++++++++++++++")
        try:
            allDevices = deviceScanner.scan(ip_range=ipRange)
            for device in allDevices:
                ipAddr.append(device['ip'].decode('ASCII'))
                try:
                    mac.append(device['mac'].decode('ASCII'))
                    macVendor.append(MacLookup().lookup(
                        device['mac'].decode('ASCII')))
                except:
                    macVendor.append("None")
                try:
                    open.append(
                        portScanner.portScanner(device['ip'].decode('ASCII'),
                                                port))
                except:
                    print("While scanning ports , got an error!")
            try:
                for i in range(len(open)):
                    tcpPorts.append(open[i].opentcp)
                    udpPorts.append(open[i].openudp)
                for i in range(len(mac)):
                    db.insertinto(self.hostIP, mac[i], ipAddr[i], macVendor[i],
                                  tcpPorts[i], udpPorts[i])
                self.createTable(ipAddr, mac, macVendor, tcpPorts, udpPorts)
            except:
                print("Got an error while creating table")

        except:
            print("Got error while getting IP Addresses!")
예제 #25
0
class DHCPDLogEntry(LogEntry):

    mac_regex = re.compile(r'''([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})''')
    mac_lookup = MacLookup()

    def __init__(self, line):
        super().__init__(line)
        self.line = line.split('dhcpd: ')[1]
        result = re.search(DHCPDLogEntry.mac_regex, line)
        if result:
            mac = result.group(0)
            try:
                vendor = DHCPDLogEntry.mac_lookup.lookup(mac)
                self.line += f' ({vendor})'
            except:
                self.line += ' (unknown vendor)'

    def __str__(self):
        return self.line
예제 #26
0
    def _method_(self, *args):

        try:
            options = args[0]
            ip = options[0]
        except IndexError:
            print('[-] Check if options are correct. [ip/24]')

        arpRequest = scapy.ARP(pdst=ip)
        broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
        arpRequestBroadcast = broadcast / arpRequest
        answered = scapy.srp(arpRequestBroadcast, timeout=1, verbose=False)[0]

        print(
            "IP\t\t\tMAC Address\t\t\tVendor\n-----------------------------------------------------------"
        )
        for el in answered:
            print(el[1].psrc + "\t\t" + el[1].hwsrc + "\t\t" +
                  MacLookup().lookup(el[1].hwsrc))
예제 #27
0
def ARPScan(IP):
    arp_request = scapy.ARP()
    arp_request.pdst = IP  # setting the IPfield in Scapy ARP packet to IP
    broadcast = scapy.Ether()
    broadcast.dst = "ff:ff:ff:ff:ff:ff"
    arp_request_broadcast = broadcast / arp_request
    answered_list, unanswered_list = scapy.srp(arp_request_broadcast,
                                               timeout=2,
                                               verbose=False)
    clients_list = []
    for answer in answered_list:
        RetrievedMACVendor = MacLookup().lookup(answer[1].hwsrc)
        client_dict = {
            "ip": answer[1].psrc,
            "mac": answer[1].hwsrc,
            "mac_vendor": RetrievedMACVendor
        }
        clients_list.append(client_dict)
    return clients_list
예제 #28
0
def getLiveConnexion():
    print("Starting monitoring mode...")
    cap = pyshark.LiveCapture(interface='wlan0mon',
                              display_filter='wlan.fc.subtype==0x0004')
    print("Listening for beacon packets..")

    list_of_probes = []
    list_of_detected_devices = []

    while (True):
        list_of_detected_devices.clear()
        list_of_probes.clear()

        start = time.time()
        end = 0

        for packet in cap.sniff_continuously():
            # Si l'adresse mac a deja etait detctée une fois, on saut ce packet.
            if packet.wlan.sa_resolved in list_of_detected_devices:
                continue
            else:
                list_of_detected_devices.append(packet.wlan.sa_resolved)

            puissance = -34
            rssi = int(packet.radiotap.dbm_antsignal)
            distance = pow(10, (puissance - rssi) / 20)
            vendor = MacLookup().lookup(packet.wlan.sa_resolved)

            probe = {
                "created_at": "{}".format(datetime.now()),
                "field1": packet.wlan.sa_resolved,
                "field2": packet.radiotap.dbm_antsignal,
                "field3": distance,
                "field4": vendor
            }

            list_of_probes.append(probe)
            end = time.time()
            #For the "for" loop.
            if end - start > 16:
                break
        print(list_of_probes)
예제 #29
0
def catalogNetwork(conn, cursor, surveyResults):
    networkId = getNetworkId(surveyResults, conn, cursor)
    
    cursor.execute('SELECT * FROM hosts WHERE networkId = ?',
        [networkId])
    hosts = { host['macAddr'] : host 
        for host in cursor.fetchall() }
    
    for host in surveyResults:
        notRecorded = (host['mac'] not in hosts.keys())
        
        #Does db ip match survey ip? (can differ in dynamic-addressed networks)
        wrongIp = (0 if notRecorded 
            else (hosts[host['mac']]['ipAddr'] != host['ip']))
        
        if notRecorded or wrongIp:
            try:
                manufacturer = MacLookup().lookup(host['mac'])
            except:
                manufacturer = 'unknown'
            
            #Upsert.
            cursor.execute('''INSERT OR ABORT INTO hosts 
                (macAddr, ipAddr, manufacturer, networkId) VALUES (?, ?, ?, ?)
                ON CONFLICT(macAddr, networkId) DO UPDATE SET ipAddr = ?;''',
                [host['mac'], host['ip'], manufacturer, networkId, host['ip']])
            
            hosts[host['mac']] = {
                'id': cursor.lastrowid,
                'macAddr': host['mac'],
                'ipAddr': host['ip'],
                'manufacturer': manufacturer,
                'networkId': networkId,
                'notificationEnabled': 0,
                'tone': 0
            }
            
    conn.commit()
    #Make dict w/ hostId as key rather than mac.
    retHosts = { host['id'] : host for _, host in hosts.items() }
    
    return retHosts
예제 #30
0
def NetworkTara(ip_araligi):

    cevaplar = []
    modemmac = ""

    nm = nmap.PortScanner()

    print("Ag Taraniyor... Lutfen Bekleyiniz...")
    a = nm.scan(ip_araligi, arguments='-sn')

    for k, v in a['scan'].items():
        if str(v['status']['state']) == 'up':
            try:
                cevaplar.append(
                    [str(v['addresses']['ipv4']),
                     str(v['addresses']['mac'])])
            except:
                pass

    if len(cevaplar) == 0:
        print("Host bulunamadi!")

    else:
        print("\n * * * * * * Blunan Hostlar * * * * * * ")
        for i in range(len(cevaplar)):

            if (cevaplar[i][0] == GetGateWay()):
                modemmac = cevaplar[i][1]

            print("[", i, "]", " - Ip :", cevaplar[i][0], "- Mac :",
                  cevaplar[i][1], "- Uretici Firma :",
                  MacLookup().lookup(cevaplar[i][1]))

        hedef = int(input("Hedefin numarasi : "))

        #giden bilgilerin formatı = [hedef_ip,hedef_mac,modemin_ip,modemin_mac]
        giden_bilgiler = [
            cevaplar[hedef][0], cevaplar[hedef][1],
            GetGateWay(), modemmac
        ]
        return giden_bilgiler