def whohas(self, ip): ans = arping(ip, verbose=False)[0] if not ans: return None return ans[0][1].hwsrc
def getHostnameByIP(ip): try: # Hostname is shown when calling this method arping(ip, retry=3, iface=programMgr.mainNICName) return None except: raise NetworkException()
def arp(): try: from scapy.all import arping arping('192.168.1.*') except ImportError: print "Couldn't Import Scapy " except KeyError: print "ARP Scan didn't work right..."
def main(): ''' this methods returns the mac address of the ip and this function also return range like if i want to find scan IP of all the range of subnet mask then like I have use like 10.0.01/24 here /24 its mean 254 and so its will scan the the subnet mask till the 254 ''' #for the single subnet mask scapy.arping('10.0.2.1') #for the multiple subnet masks scapy.arping('10.0.2.1/24')
def get_host(): #得到在线主机的mac地址和对应ip地址 hw_ip = {} sys.stdout = open('host.info','w') arping(IPADDR) sys.stdout = stdout f = open('host.info','r') info = f.readlines() f.close del info[0] del info[0] for host in info : temp = re.split(r'\s+',host) hw_ip[temp[1]] = temp[2] return hw_ip
def scanbrs(self): '''扫描网段,获取邻居信息 Args: None Returns: devnbrs: 每个网络接口直连设备的信息,格式为: [{'dev': '接口1', nbrs: [{'ip': '邻居ip', 'mac': '邻居mac'}, ...]}, ...] 其他:参考ssh_tools.get_cmd_ret()、self.getsubnet()的返回值 ''' devnbrs = [] devnets = self.getnets() for dev in self.getnets(): if dev == 'lo' or devnets[dev] == []: continue devnbr = {'dev': dev, 'nbrs': []} for inet in devnets[dev]: subnet = self.getsubnet(inet) if type(subnet) == int: return ('err', subnet) try: ans, unans = arping(subnet, verbose=0) except socket.error, e: (etype, evalue, etrace) = sys.exc_info() (errno, err_msg) = evalue return (errno, err_msg) #ans是一个队列,每个队列元素是(发送的数据包,收到的回复包)形式的元组 if len(ans) > 0: for s, r in ans: #收到的包是ether包,arp信息在payload属性中 devnbr['nbrs'].append({'ip': r.payload.psrc, 'mac': r.src}) if devnbr['nbrs'] != []: #过滤掉没有搜索到邻居的接口 devnbrs.append(devnbr)
def findlocalneighbors(network, response): debug('ARP sweeping %s' % network.netblock) # e = Netblock(network.netblock) # e += Label('CIDR Notation', repr(network)) # e += Label('Network Mask', network.netmask) # e += Label('Number of Hosts', int(~network.netmask) - 1) # response += e ans = arping(repr(network), timeout=config['scapy/sr_timeout'], verbose=config['scapy/sr_verbose'])[0] for i in ans: e = IPv4Address(i[1].psrc) e.internal = True e += Field('ethernet.hwaddr', i[1].hwsrc, displayname='Hardware Address') response += e if len(ans) <= 1: passivescan(network, response) return response
def scan(ip_range): ip_add_range_pattern = re.compile("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]*$") while True: ip_add_range_entered = ip_range if ip_add_range_pattern.search(ip_add_range_entered): break arp_result = scapy.arping(ip_add_range_entered)
def discovery(): # DISCOVER HOSTS ON NETWORK USING ARPING FUNCTION print( "\n\n----- Discovery hosts on network using arping() function ---------------------" ) ans, unans = scapy.arping(DISCOVERY_SUBNET) ans.summary() for res in ans.res: print(f"oooo> IP address discovered: {res[0].payload.pdst}") ip_addr = res[1].payload.psrc mac_addr = res[1].payload.hwsrc try: hostname = socket.gethostbyaddr(str(ip_addr)) except (socket.error, socket.gaierror): hostname = str(ip_addr), [], [str(ip_addr)] last_heard = str(datetime.now())[:-3] host = { "ip_address": ip_addr, "mac_address": mac_addr, "hostname": hostname[0], "last_heard": last_heard, "availability": True, #"open_tcp_ports": list() } update_host(host)
def run(self): try: self.conn = sqlite3.connect(self.dbfile) with self.conn: c = self.conn.cursor() while True: try: c.execute(self._QUERY) devices = list(sum(c.fetchall(), ())) if devices: ans, unans = arping(devices, iface=None, verbose=0) for device in ans: if check_preconditions(device[1][ARP].psrc, device[1][ARP].hwsrc): insert_or_update_fingerprint( self.conn, ip=device[1][ARP].psrc, mac=device[1][ARP].hwsrc) self.logger.info("checked no mode devices: " + str(devices)) time.sleep(self._SLEEP) except sqlite3.Error as sqle: self.logger.error("a database error occurred") self.logger.exception(sqle) except sqlite3.Error as sqle: self.logger.error( "Failed to connect to sqlite database at path %s" % (self.dbfile, )) self.logger.exception(sqle) raise DaemonError()
def main(): # command line arguments: '163.26.68.*' nets = sys.argv[1:] # script path base_path = os.path.dirname(os.path.abspath(__file__)) # db filename db_file = os.path.join(base_path, 'ipmac.db') conn = sqlite3.connect(db_file) c = conn.cursor() '''begin''' conf.verb = 0 for net in nets: ans, unans = arping(net, timeout=2, inter=0.005) for sndu, rcv in ans: mac, ip = rcv.sprintf(r"%Ether.src%,%ARP.psrc%").split(",") eui = EUI(mac) org = '' # lookup organization try: oui = eui.oui org = oui.registration().org except: pass c.execute( "INSERT INTO ipmac (ip, mac, org) VALUES (?, ?, ?)", (ip, str(eui), org)) '''end''' conn.commit() conn.close()
def get_host(): #得到在线主机的mac地址和对应ip地址 hw_ip = {} sys.stdout = open('host.info', 'w') arping(IPADDR) sys.stdout = stdout f = open('host.info', 'r') info = f.readlines() f.close del info[0] del info[0] for host in info: temp = re.split(r'\s+', host) hw_ip[temp[1]] = temp[2] return hw_ip
def findlocalneighbors(network, response): debug('ARP sweeping %s' % network.netblock) e = Netblock(network.netblock) e += Label('CIDR Notation', repr(network)) e += Label('Network Mask', network.netmask) e += Label('Number of Hosts', int(~network.netmask) - 1) response += e ans = arping( repr(network), timeout=config['scapy/sr_timeout'], verbose=config['scapy/sr_verbose'] )[0] for i in ans: e = IPv4Address(i[1].psrc) e.internal = True e += Field('ethernet.hwaddr', i[1].hwsrc, displayname='Hardware Address') response += e if len(ans) <= 1: passivescan(network, response) return response
def __init__(self, addresses="192.168.1.*"): print 'searching ' + addresses print 'should find/add devices now (indicated by [FOUND])...' # find all MAC address -> IP mappings self.addresses = addresses ans, unans = arping(addresses) # add them to a dict for r in ans: mac = r[1].hwsrc ip = r[1].psrc self.mac_to_ip[mac] = ip print '\n' # run through MAC addresses in config and see if we have an IP for oc in config.outlets: ip = self.networking__lookup_mac(oc[2]) # if we do, add it to outlet_configs and add the device to outlets if ip is not None: self.outlet_configs.append((oc[0], oc[1], ip)) self.outlets.append(pytuya.OutletDevice(oc[0], ip, oc[1])) print '[FOUND] found and added ' + str(oc[0]) + \ ', device #' + str(len(self.outlets)-1) print '\nDone searching.\n'
def get_devices_identities(ips): answers, _ = arping(ips, verbose=0) NetworkIdentity = namedtuple('NetworkIdentity', ['ip', 'mac']) return [ NetworkIdentity(ip=answer[1].psrc, mac=answer[1].hwsrc) for answer in answers ]
def action_check_device(arg): # import inside function, because import is slow from scapy.all import arping if not check_ip(arg): return False # default for timeout is 2 seconds return bool(len(arping(arg, timeout=1.2, iface=None, verbose=0)[0]))
def make_target(ip): ans, unans = arping(ip) conf.verb = 0 for snd,rcv in ans: ipv4 = ip mac = rcv[Ether].src manu = find_vendor(mac) return Target(ipv4, mac, manu)
def __init__(self, addresses="192.168.1.*"): self.addresses = addresses ans, unans = arping(addresses) for r in ans: mac = r[1].hwsrc ip = r[1].psrc self.mac_to_ip[mac] = ip
def arp_scan(ip_space): macs = [] ans_pkts, _ = arping(ip_space, verbose=0) for pkt in ans_pkts: m = pkt[1].sprintf("%Ether.src%") m = '-'.join(m.split(':')).lower() macs.append(m) return macs
def get_host(): mac_ip = {} sys.stdout = open('host.info', 'w') arping(IPADDR) sys.stdout = stdout f = open('host.info', 'r') info = f.readlines() f.close() for host in info: tmp = re.split(r'\s+', host) if len(tmp) != 4: continue mac_ip[tmp[1]] = tmp[2] return mac_ip
def get_host(self): hostip = self.get_ipaddress() mask = str(self.get_netmask()) res = arping( hostip + '/' + mask, timeout=self.timeout, iface=self.ifname) hostlist = {} for eachenty in res[0].res: ip = eachenty[0].pdst hostlist[ip] = eachenty[1].src return hostlist
def arp_scan(self): """ Scan using Scapy arping method """ if self.router_mac and self.router_mac == GLOBAL_MAC: self.init() self.generate_ips() scan_result = arping(f"{self.router_ip}/24", verbose=0, timeout=1) clean_result = [(i[1].psrc, i[1].src) for i in scan_result[0]] self.devices_appender(clean_result)
def IP_Address(addr): ui.textEdit.append('Scanning IP addresses....') ui.textEdit.repaint( ) # for update the textEdit immediately not wait to all function to finish # Try ARPing the ip address range supplied by the user. # The arping() method in scapy creates a pakcet with an ARP message # and sends it to the broadcast mac address ff:ff:ff:ff:ff:ff. # If a valid ip address range was supplied the program will return # the list of all results. ans, unans = scapy.arping(addr) return ans
def __scan_network(network_id: str, verbose: bool) -> List[Device]: scan_data: List[Device] = [] answered, _ = arping(network_id, verbose=verbose) for s, r in answered: mac_address = r[Ether].src ip_address = s[ARP].pdst hostname, aliases, _ = socket.gethostbyaddr(ip_address) scan_data.append(Device(mac_address, ip_address, hostname, aliases, external.get_mac_address_vendor(mac_address))) return scan_data
def update_cache(self): try: ans, unans = arping(self._router_ip + "/24", iface=self._interface, verbose=False) self._arp_cache = [] if ans: for s, r in ans: self._arp_cache.append([r[ARP].psrc, r[Ether].src.lower()]) _LOGGER.debug("ARP cache: %s", self._arp_cache) except Exception as e: _LOGGER.error("Error when trying update ARP cache: %s", str(e))
def scan_arp(ip): target_ip = ip ssh_port, telnet_port = 22, 23 try: ans, unans = scapy.arping(target_ip, verbose=0) for an in ans: return [an[1].sprintf("%ARP.psrc%"), an[1].sprintf("%Ether.src%"), \ get_info(an[1].sprintf("%Ether.src%")), \ scan_port(an[1].sprintf("%ARP.psrc%"), ssh_port), \ scan_port(an[1].sprintf("%ARP.psrc%"), telnet_port)] \ except Exception as e: print("Error !".format(e)) print(e) return
def getmacs(self, target): ret = {'ip_mac': {}, 'mac_ip': {}} log.msg('arping in progress') ans, unans = scapy.arping(target) log.msg('finished') for a in ans: # a[1].show() mac = a[1][scapy.ARP].hwsrc ip = a[1][scapy.ARP].psrc if mac in ret['mac_ip']: ret['mac_ip'][mac].append(ip) else: ret['mac_ip'][mac] = [ip] ret['ip_mac'][ip] = mac return ret
def __scan_network(network_id: str, verbose: bool, plugin_config: dict) -> List[DiscoveredDevice]: """ Built in method to scan a network """ scan_data: List[DiscoveredDevice] = [] answered, _ = arping(network_id, verbose=0) for s, r in answered: mac_address = r[Ether].src ip_address = s[ARP].pdst hostname = socket.getfqdn(ip_address) scan_data.append(DiscoveredDevice(mac_address, ip_address, hostname)) return scan_data
def getmacs(self, target): ret = {'ip_mac': {}, 'mac_ip': {}} log.msg('arping in progress') ans,unans = scapy.arping(target) log.msg('finished') for a in ans: # a[1].show() mac = a[1][scapy.ARP].hwsrc ip = a[1][scapy.ARP].psrc if mac in ret['mac_ip']: ret['mac_ip'][mac].append(ip) else: ret['mac_ip'][mac] = [ip] ret['ip_mac'][ip] = mac return ret
def get_host(self): if hasattr(self, 'hostlist'): return self.hostlist hostip = self.get_ipaddress() mask = str(self.get_netmask()) res = arping( hostip + '/' + mask, timeout=self.timeout, iface=self.ifname) self.hostlist = {} for eachenty in res[0].res: ip = eachenty[0].pdst self.hostlist[ip] = eachenty[1].src #print(self.hostlist) return self.hostlist
def scan_devices(subnet_set): ans_lists = set() dev_list = set() for subnet in subnet_set: ans, unans = arping(str(subnet)) ans_lists.add(ans) for ans in ans_lists: for dev in ans: company = mac_lookup(dev[1].src) new_dev = (dev[1].psrc, dev[1].src, company) dev_list.add(new_dev) return dev_list
def getScan(): # scan result = arping("192.168.1.0/24", timeout=2)[0] # map all clients clients = [] for sent, received in result: manuf = scapyConf.manufdb._get_short_manuf(received.hwsrc) manuf = "unknown" if manuf == received.src else manuf clients.append({ 'ip': received.psrc, 'mac': received.hwsrc, 'manuf': manuf }) return jsonify(clients)
def arp_scan(ip_range): """We use the arping method in scapy. It is a better implementation than writing your own arp scan. You'll often see that your own arp scan doesn't pick up mobile devices. You can see the way scapy implemented the function here: https://github.com/secdev/scapy/blob/master/scapy/layers/l2.py#L726-L749 Arguments: ip_range -> an example would be "10.0.0.0/24" """ # We create an empty list where we will store the pairs of ARP responses. arp_responses = list() # We send arp packets through the network, verbose is set to 0 so it won't show any output. # scapy's arping function returns two lists. We're interested in the answered results which is at the 0 index. answered_lst = scapy.arping(ip_range, verbose=0)[0] # We loop through all the responses and add them to a dictionary and append them to the list arp_responses. for res in answered_lst: # Every response will look something lke like -> {"ip" : "10.0.0.4", "mac" : "00:00:00:00:00:00"} arp_responses.append({"ip": res[1].psrc, "mac": res[1].hwsrc}) # We return the list of arp responses which contains dictionaries for every arp response. return arp_responses
def getMACByIP(ip): try: ans, unans = arping(ip, retry=3, iface=programMgr.mainNICName) for snd, rcv in ans: return rcv.sprintf(r"%Ether.src%") subprocess.run(['powershell.exe', f'ping {ip}'], capture_output=False, shell=False) p = subprocess.run(['powershell.exe', f'arp -a | findstr {ip}'], capture_output=True) arpInfo = p.stdout.decode('utf-8').split() if len(arpInfo) > 1: return arpInfo[1] return None except: raise NetworkException()
def scan_arp(addresses): """ Call arping from scapy and return information about active users. Args: addresses -- Range of addresses. Returns: Dictionary with users info (key users) and date of scan (key date). """ logging.info('Starting scanning.') answers, _ = arping(addresses, verbose=False) logging.info('Ended scanning.') date = datetime.today() datestring = date.isoformat(' ', 'seconds') users = {} for answer in answers: users[answer[1].getlayer(ARP).hwsrc] = answer[1].getlayer(ARP).psrc return {'users': users, 'date': datestring}
def local_map(local): # Check out the visible network beacons beacons = beacon_sniff() # Display info about beacons found print CITAL + str(len( beacons['mac'])) + " Wireless Access Points Identified" + CEND if len(beacons['mac']) > 0: os.system( 'paplay /lib/live/mount/rootfs/filesystem.squashfs/usr/share/' 'metasploit-framework/data/sounds/default/wonderful.wav') print CBOLD + CGREEN + "MAC\t\tESSID\t\tCHANNEL/FREQUENCY" + CEND if len(beacons['mac']) == len(beacons['essid']) == len( beacons['channel']): for i in range(len(beacons['mac'])): print CBOLD + CRED + beacons['mac'].pop() + "\t" + CEND + \ CBOLD + CBLUE + beacons['essid'].pop() + "\t" + CEND + \ CBOLD + CPURP + beacons['channel'].pop() + "\t" + CEND os.system('rm neighborhood.txt') # Move on to identifying hosts in Local Network live_hosts = [] # Ping any hosts connected to the same subnet os.system('./hellolan.sh >> hosts.txt') possible_neighbors = swpobj('hosts.txt') os.system('rm hosts.txt') print "\t\t" + CBOLD + CITAL + "FINDING LIVE HOSTS ON LAN" + CEND for line in possible_neighbors: try: live_hosts.append(line.split(' domain name pointer ')[1]) except IndexError: pass for host in live_hosts: print CBOLD + "Found Live Host: " + CWHBLK + host + CEND os.system('paplay /lib/live/mount/rootfs/filesystem.squashfs/usr/share/' 'metasploit-framework/data/sounds/default/excellent.wav') try: ans = scapy.arping("192.168.1.*") print ans except: pass return live_hosts, beacons
def __scan_network(network_id: str, verbose: bool, plugin_config: dict) -> List[DiscoveredDevice]: """ Built in method to scan a network """ scan_data: List[DiscoveredDevice] = [] try: answered, _ = arping(network_id, verbose=0) except Scapy_Exception as exception: # This happens when running the module using python in the cmd # Interface is invalid (no pcap match found) ! raise ScanException("Npcap must be installed for Windows hosts") except OSError as exception: # This happens when running the application using the vs code launch config # b'Error opening adapter: The system cannot find the device specified. (20)' raise ScanException("Npcap must be installed for Windows hosts") for s, r in answered: mac_address = r[Ether].src ip_address = s[ARP].pdst hostname = socket.getfqdn(ip_address) scan_data.append(DiscoveredDevice(mac_address, ip_address, hostname)) return scan_data
def scan_and_print_neighbors(net): ans,unans = scapy.arping(net, timeout=1, verbose=False) for s,r in ans.res: hostname = socket.gethostbyaddr(r.psrc) print r.sprintf("%Ether.src% %ARP.psrc%"), print " ", hostname[0]
try: conf.iface = argv[2] except Exception as prblm: exit(prblm) print "Iface ", conf.iface elif "-a" in argv or "-A" in argv: pass elif "-s" in argv or "-S" in argv: get_data = Ether()/ARP(op = 1, ptype = 0x800, hwlen = 6, plen = 4) my_ip = get_data[ARP].psrc index = my_ip.rfind(".") print "ARP Scan %s%s" % (my_ip[:index+1], "/24") try: ans, unans = arping(my_ip[:index+1] + "*" , verbose=0, timeout=10) except Exception as problm: exit(str(problm) + "\n[Info] you need to be root") if len(ans) > 0: for i in ans: print i[0][ARP].pdst + " -- " + i[1][Ether].src else: print "Got no Response" exit() elif "-e" in argv or "-E" in argv: pass elif "-u" in argv or "-U" in argv: if "mitm_data" in listdir("."): remove("mitm_data")
def scan(self): ans, _ = arping(self._subnet, verbose=False) for x in ans: self.notify_observers(x[1][ARP].psrc)