Exemplo n.º 1
0
def ScanWIFI(card):
    try:
        wifiCell = Cell.all(card)
    except:
        wifiCell = Cell.all('wlan0')
        SendData("Something went wrong... using wlan0")
    for i in range(0,len(wifiCell)):
        SendData(str(wifiCell[i]) + " is encrypted: "+ str(wifiCell[i].encrypted) + "= " + str(wifiCell[i].encryption_type) + " | address: " +str(wifiCell[i].address))
    SendData("ScanWIFI-finished")
Exemplo n.º 2
0
def wifi_scan():
	global connected

	reconnected = 0
	while 1:
		print "Reconnected %d" %reconnected
#Connected, check if still in range
		if connected != "":
			aps = Cell.all(interface)
			inrange = 0
			for ap in range(0, len(aps)):
				if aps[ap].ssid == connected and aps[ap].signal <= -50:
					inrange = 1
			if inrange != 1:
				connected = ""
			else:
				time.sleep(20)
				
#Not connected
		else:
			
			aps = Cell.all(interface)
			for ap in range(0, len(aps)):
				if aps[ap].ssid in known_ssids:
					passwd = known_ssids_pass[known_ssids.index(aps[ap].ssid)]
					scheme = Scheme.for_cell(interface, "target", aps[ap], passwd)
					scheme.delete()
					scheme.save()
					try:
						scheme.activate()
						connected = aps[ap].ssid
						reconnected += 1
						break
					except:
						print "Could not connect"
						continue
					#connect to the AP and stop scanning (return connected = ssid?)
			else:
				for ap in range(0, len(aps)):
					if aps[ap].encrypted == False and connected == "":
						scheme = Scheme.for_cell(interface, "target", aps[ap])
						scheme.delete()
						scheme.save()
						try:
							scheme.activate()
							connected = aps[ap].ssid
							reconnected += 1
							break
						except:
							print "could not connect"
							continue
					else:
						time.sleep(10)
Exemplo n.º 3
0
    def scan(self):
        print "Scan Start"
        while True:
            cell = Cell.all(interface)
            print "Rescanning"
            timer = 0
            while timer < 100:
                timer +=1
                S = []
                count = 0
                for c in cell:
                    count += 1
                    #print ":"+ str(count), " ssid:", c.ssid
                        #create dictionary with informnation on the accesss point
                    SSIDS = {"no" : count ,"ssid": c.ssid, "channel":c.channel,"encrypted":c.encrypted, \
                                "frequency":c.frequency,"address":c.address, "signal":c.signal, "mode":c.mode}

                    #if not db.search((where('ssid') == ap["ssid"])) == []:
                   # res =  db.search(where('ssid') == c.ssid)
                    #print db.search(where('ssid') == c.ssid)
                    
                    print  "=----------------------------------"
                   # print  c.address
                    print "---------------------------------------"
                    if db.contains(where('ssid') == c.ssid):
                        print (db.contains((where('ssid') == c.ssid) & (where('address') == str(c.address))))
Exemplo n.º 4
0
 def new_wifi_connection(self):
     ssids = [cell.ssid for cell in Cell.all('wlan0')]
     if len(ssids) > 0:
         ssid = ssids[self.ui.select_from_list(ssids,display_message="Select SSID",controls=False)]
     pwd = self.ui.enter_text("Enter SSID pwd",Menu.space+Menu.letters+Menu.numbers+Menu.symbols)
     self.core.setup_wifi_connection(ssid,pwd)
     return self.edit_wifi_menu
Exemplo n.º 5
0
def getWifiNetworks():
	l=[]
	i=0
	scanned=False
	while not scanned and i<3:
		l=[]
		try:
			for cell in Cell.all('wlan0'):
				try:
					name=str(cell.ssid)
					if len(name.strip())>1:
						enc="None"
						if cell.encrypted:
							enc=cell.encryption_type
						l.append((cell.signal,cell.encrypted,cell.ssid,enc))
						
				except:
					logging.warning("Failed to use cell, %s" , cell.ssid)
			scanned=True
		except: # please lets move this (wpa_cli scan / wpa_scan_results ? )
			i+=1
			time.sleep(1)
	l.sort(reverse=True)
	print l
	return l
 def handler(self):
     if receive == 'scan':
         print 'Connection from {}'.format(str(self.addr))
         print 'Status: {}'.format(receive)
         file = open('/etc/wpa_supplicant/wpa_supplicant.conf', 'r')
         currentWifi = file.readlines()
         dataSplit = currentWifi[4].split('ssid="')[1]
         currentSSID = dataSplit.split('"')[0]
         file.close()
         data = Cell.all('wlan0')
         self.clientsocket.send(str(len(data)) + '\r\n')
         self.clientsocket.send(currentSSID + '\r\n')
         for i in range(len(data)):
             splitSSid = str(data[i]).split('=')[1]
             self.clientsocket.send(str(splitSSid.split(')')[0]) + '\r\n')
         print 'Exit ScanWifi'
         
     if 'modify' in receive:
         print 'Status: {}'.format(receive)
         ssid = receive.split(':')[1]
         password = receive.split(':')[2]
         editFile = open('/etc/wpa_supplicant/wpa_supplicant.conf','w')
         editFile.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
         editFile.write('update_config=1\n')
         editFile.write('\nnetwork={\n     ssid="')
         editFile.write(ssid)
         editFile.write('"\n     psk="')
         editFile.write(password)
         editFile.write('"\n}')
         editFile.close()
         print 'Exit Modify Wifi'
         os.system("sudo reboot")
Exemplo n.º 7
0
    def __init__(self):
        '''
        Constructor method
        '''

        # Default directory & interface
        self.cwd = os.getcwd()
        self.iface = 'wlan0'

        # Try to get wireless gateway details,
        # unless there's no active connection
        try:
            self.ping_ip, self.gw_mac = self.getGateway()
        except:
            self.ping_ip = self.gw_mac = None
            print('Error! \nCheck your connection!')
        finally:
            pass

        # Get the Gateway SSID
        try:
            cell = Cell.all(self.iface)
            x, y = str(list(cell)[0]).split('=')
            self.ssid = y.strip(')')
        except:
            self.ssid = 'Offline'
Exemplo n.º 8
0
def sample_interface_neighbourhood(network_interface, networks = None, network_states = None):
	"""sample interface neighbourhood"""

	networks = networks if networks else {}
	network_states = network_states if network_states else {}

	timestamp = str(datetime.datetime.now())
	cells = Cell.all(network_interface)

	for cell in cells:

		network_key = render_network_key(cell.ssid, cell.address)

		if network_key not in networks.keys():

			network = new_network(
				cell.address, cell.ssid, cell.frequency,
				cell.encryption_type if cell.encrypted else None, cell.encrypted, cell.mode,
				cell.bitrates, cell.channel)

			networks[network_key] = network
			network_states[network_key] = new_network_state()

		network_state = network_states[network_key]

		network_state['time'].append(time)
		network_state['signal'].append(cell.signal)
		network_state['quality'].append(cell.quality)

	return networks, network_states
Exemplo n.º 9
0
def wifiNetworkSearch(wifiNetwork,wifiRetries,sleepSec=2):
    for k in range(0,3): #Sometimes this will fail if the system is trying to access at the same time
        try:
            logging.debug("Looking for an X2 Wi-Fi network...")
            for i in range(0,wifiRetries):
                ssids=[cell.ssid for cell in Cell.all('wlan0')]
                logging.debug("\nList of all networks found: ")
                for value in ssids: #loop through and print found network names
                    logging.debug(value)
                for ssid in ssids: #loop through found networks and scan for SSID
                    if (wifiNetwork in ssid):
                        done=True
                        logging.debug("Attempt %d of %d was successful",i+1,wifiRetries)
                        logging.debug("Found network: %s",ssid)
                        break
                    else:
                        done=False
                if(done):
                    logging.debug("Successfully found the Wi-Fi network\n")
                    return "Pass"
                else:
                    logging.debug("Failed to find a network with %s in it on attempt %d of %d", wifiNetwork, i+1, wifiRetries)
                    if(i+1<wifiRetries):
                        logging.debug("Waiting %d seconds and retrying...",sleepSec)
                        time.sleep(sleepSec)
                    else:
                        logging.debug("Failed to find X2 network\n")
                        return "Fail-Network not found"
        except:
            time.sleep(2)
            logging.debug("Wi-Fi network resource busy on attempt %d of 3",k+1)
            pass
    else:
        return "Fail-RPi was using the Wi-Fi resource"
Exemplo n.º 10
0
def locate():
	aps = {}
	try:
		from wifi import Cell
	except:
		pass
	else:
		interfaces = netifaces.interfaces()
		for interface in interfaces:
			try:
				cells = Cell.all(interface)
			except:
				pass
			else:
				for ap in cells:
					strength = [int(i) for i in ap.quality.split('/')]
					aps[ap.address] = 0-int(strength[0]/strength[1]*100)	

	try:
		import NetworkManager
		manager = NetworkManager.NetworkManager
	except:
		pass
	else:
		for dev in manager.GetDevices():
			sdev = dev.SpecificDevice()
			if sdev.__class__.__name__ == 'Wireless':
				for ap in sdev.GetAccessPoints():
					aps[ap.HwAddress] = 0-ord(ap.Strength)
				
	data = urllib.parse.urlencode([('wifi', 'mac:%s|ss:%d' % (mac, strength)) for mac, strength in aps.items()])
	f = urllib.request.urlopen('https://maps.googleapis.com/maps/api/browserlocation/json?browser=python&sensor=true&%s' % data)
	response = json.loads(f.read().decode('utf-8'))
				
	return response['location']['lat'], response['location']['lng'], response['accuracy']
Exemplo n.º 11
0
 def run(self):
     #try:
     #print Cell.all(self.interface)[0]
     cell = Cell.all(self.interface)[0]
     scheme = Scheme.for_cell(self.interface, self.ssid, cell, self.passphrase)
     #scheme.save()
     self._return = scheme.activate()
    def get_location(self):

        """Obtains the physical location using nearby Wi-Fi networks.

        :returns: a Dict containing the lat & lon for the current location.

        According to Google's API specification, two or more access points are
        required for a result to be returned. In case a result is not returned,
        or another error occurs, a LocationError is raised.
        """

        # Get full information for all visible access points
        networks = Cell.all(self.interface)
        addresses = []

        # Extract just the MAC addresses
        for network in networks:
            addresses.append({'macAddress': network.address})

        json_response = requests.post(
            GOOGLE_LOCATION_URL.format(GOOGLE_API_KEY),
            data=json.dumps({'wifiAccessPoints': addresses}),
            headers=JSON_REQUEST_HEADERS
        ).json()

        # Handle Google returning an error.
        if "error" in json_response:
            raise LocationError("Unable to determine location")
        else:
            return {
                'lat': json_response['location']['lat'],
                'lon': json_response['location']['lng']
            }
Exemplo n.º 13
0
	def ScanForNetworks(self):
	    cells = Cell.all(WIRELESS)
	    listOfCells = []
	    for cell in cells:
	        if str(cell.ssid) not in listOfCells:
	            listOfCells.append(str(cell.ssid))
	    return(listOfCells)
Exemplo n.º 14
0
    def scan(self, event=None):
        LOG.info("Scanning wifi connections...")
        networks = {}
        status = self.get_status()

        for cell in Cell.all(self.iface):
            if "x00" in cell.ssid:
                continue  # ignore hidden networks
            update = True
            ssid = cell.ssid
            quality = self.get_quality(cell.quality)

            # If there are duplicate network IDs (e.g. repeaters) only
            # report the strongest signal
            if networks.__contains__(ssid):
                update = networks.get(ssid).get("quality") < quality
            if update and ssid:
                networks[ssid] = {
                    'quality': quality,
                    'encrypted': cell.encrypted,
                    'connected': self.is_connected(ssid, status)
                }
        self.ws.emit(Message("mycroft.wifi.scanned",
                             {'networks': networks}))
        LOG.info("Wifi connections scanned!\n%s" % networks)
Exemplo n.º 15
0
def testWifi(GPIO,pinDict,x2,mbRetries,wifiNetwork,wifiRetries):
    powerOn(GPIO,pinDict,"IO1")
    print ("=====================")
    print (datetime.datetime.now().strftime("%Y.%m.%d_%H.%M.%S"))
    print ("=====================")

    #NEED TO TURN ON WIFI SWITCH

    searchString=wifiNetwork
    retries=wifiRetries
    sleepSec = 2

    for i in range(0,retries):
        ssids=[cell.ssid for cell in Cell.all('wlan0')]
        print("List of all networks found:",ssids)
        for ssid in ssids:
            if (searchString in ssid):
                done=True
                print("Attempt", i+1, "of", retries, "was successful")
                print("Found network:",ssid)
                break
            else:
                done=False
        if(done):
            return ["Pass"]
        else:
            print("Failed to find a network with", searchString, "in it on attempt", i+1, "of", retries)
            if(i+1<retries):
                print("Waiting", sleepSec, "seconds and retrying...")
                time.sleep(sleepSec)
            else:
                print("Failed to find X2 network")
                return ["Fail-Network not found"]
def scanWifi():
	while 1:
		cellName =None
		cellList = Cell.all('wlan0')


		print "Scan Around Cell"

		for cell in cellList:
			if cell.ssid == 'carcar5':
				cellName =cell


		if cellName is None:
			print "Can not found <carcar5> try again"
			time.sleep(1)
			continue
		else :
			temp = Scheme.find('wlan0','home')
			if temp is not None:
				temp.delete()

			scheme = Scheme.for_cell('wlan0', 'home',cellName, passKey)
			scheme.save()
			scheme.activate()
				
			print "Try connect to <carcar5>"
			myIp = commands.getoutput("hostname -I")
			print "Connection Success my Ip is : " + myIp
			return True
Exemplo n.º 17
0
		def scan(iface):
			exp_backoff=1
			for _ in range(5):
				results = []
				for cell in Cell.all(iface):
					c = {
						'ssid': cell.ssid,
						'frequency': cell.frequency,
						'bitrates': cell.bitrates,
						'encrypted': cell.encrypted,
						'channel': cell.channel,
						'address': cell.address,
						'mode': cell.mode,
						'quality': cell.quality,
						'signal': cell.signal
					}
					if cell.encrypted:
						c['encryption_type'] = cell.encryption_type
					results.append(c)
	
				results.sort(key=lambda x: x['signal'], reverse=True)
				if (len(results) > 0):
					break
				sleep(exp_backoff)
				exp_backoff *= 2
				#retry
			return jsonify(results=results)
    def get(self):
        cells = Cell.all('wlan0')
        items = []
        for cell in cells:
            items.append(cell.__dict__)

        self.write(json.dumps(items))
Exemplo n.º 19
0
 def get_networks(self):
     '''get a list of networks...'''
     networks = Cell.all(self.interface)
     if networks:
         return networks
     else:
         logging.warn("Unable to find networks - Interface {}".format(self.interface))
         return []
Exemplo n.º 20
0
def get_available_networks():
    """ Returns a list of available wifi networks """
    try:
        ssids = [[cell.ssid, cell.encrypted] for cell in Cell.all('wlan1')]
    except:
        print "Error getting available networks; is iwlist available on your machine?"
    json_output = json.dumps(ssids)
    return json_output
Exemplo n.º 21
0
 def wifi_scan(self, iface):
     l = []
     print "[*] Scanning on: %s" % str(iface)
     self.ssid_list = Cell.all(iface)
     self.ssid_list_len = len(self.ssid_list)
     self.wli = -1
     for i in xrange(self.ssid_list_len):
         l.append(unicode(self.ssid_list[i]))
     return l
Exemplo n.º 22
0
def wifi_scan(iface):
    l = []
    print "scanning on %s" % str(iface)
    global ssid_list
    ssid_list = Cell.all(iface)
    ssid_list_len = len(ssid_list)
    for i in xrange(ssid_list_len):
        l.append(unicode(ssid_list[i]))
    return (l)
Exemplo n.º 23
0
def log_ssids():
    """
    scan for local Wifi points and log the SSID's to file
    """
    print('Scanning for wifi access points...')
    ssids = [cell.ssid for cell in Cell.all('wlan0')]
    with open('ssids.lis', 'w') as f:
        for s in ssids:
            f.write(s + '\n')
Exemplo n.º 24
0
def scanForParrots(interface, whitelist, underattack):
	aps = Cell.all(interface)
	parrots = []
	for ap in aps:
		if ap.address.startswith('90:03:B7') or ap.address.startswith('00:26:7E') or ap.address.startswith('A0:14:3D') or ap.address.startswith('00:12:1C') or ap.address.startswith('58:44:98:13:80'): #if it is a parrot OR my phone (for testing)
			if ap.address not in whitelist and ap.address not in underattack: #only add if new and not on the whitelist
				logging.info("New parrot wifi found: %s", ap.ssid)
				arduinoLCD("New:" + ap.ssid)
				parrots.append(ap)
	return parrots
Exemplo n.º 25
0
 def scan(self):
     network = list()
     try:
         self.cells = Cell.all(self.interface)
         for n in self.cells:
             ssid = n.ssid
             if ssid is not None and ssid != "":
                 network.append(ssid)
         self.networks["ssid"] = network
     except Exception, e:
         self.networks["message"] = str(e)
         self.networks["error"] = True
Exemplo n.º 26
0
 def get_near_networks(self):
     cells = Cell.all(self.iface)
     for cell in cells:
         if cell.ssid in self.ssids:
             if self.find_scheme(cell.ssid):
                 print "Found a Network to connect to."
                 self.activate_scheme(cell.ssid)
             else:
                 print "Connecting to: %s" % cell.ssid
                 self.create_scheme(cell.ssid, self.passwords[self.ssids.index(cell.ssid)])
         else:
             print "Found no Network to connect to."
Exemplo n.º 27
0
 def get_networks(self):
     """get a list of networks
     :rtype : wifi cell
     """
     try:
         networks = Cell.all(self.interface)
         if networks:
             return networks
         else:
             logging.warn("Unable to find networks - Interface {}".format(self.interface))
             return []
     except Exception as e:
         logging.warn("could not get networks: {}".format(e))
Exemplo n.º 28
0
def plot_channel_data(frame):
    plt.cla()
    for c in Cell.all(interface):
        ch = c.channel
        s = 100 + c.signal

        x = np.linspace(ch-2, ch+2, 50)
        y = s * np.sin((x - ch + 2) / 4 * np.pi)

        col = get_color(c.ssid + c.address)

        plt.fill(x, y, col, alpha=0.3)
        plt.annotate(c.ssid, (ch, s))
Exemplo n.º 29
0
def connect_to_ap(log):
    """Function that will connect to wifi with the given parameters"""

    log.log("Connecting to " + WIFI_SSID + " using " + WIFI_INTERFACE)

    # Complicated way to account for the file not existing
    # Just tries to find if a scheme exists in interfaces
    try:
        scheme = Scheme.find(WIFI_INTERFACE, WIFI_PROFILE)
    except(IOError,err):
        log.log(err)
        log.log("WARNING: Most likely file was not found. Making one.")
        scheme = None
        if not os.path.isdir(INTERFACE_DIR):
            os.mkdir(INTERFACE_DIR, 0755)
            os.open(INTERFACE_FILE, 0644).close()
        elif not os.path.isfile(INTERFACE_FILE):
            os.open(INTERFACE_FILE, 0644).close()

    # If the scheme was not found or if it was found and didn't activate,
    # look for the ssid, save it, and connect to it.
    if scheme == None:
        cells = Cell.all(WIFI_INTERFACE)
        for cell in cells:
            if cell.ssid == WIFI_SSID:
                scheme = Scheme.for_cell(WIFI_INTERFACE,
                                         WIFI_PROFILE,
                                         cell,
                                         passkey=WIFI_PASS)
                scheme.save()
                break
    if scheme == None:
        log.log("ERROR: SSID " + WIFI_SSID + " was not found.")
        return False

        if scheme.activate() == False:
            log.log("ERROR: Could not connect to " + WIFI_SSID + ".")
            return False
    else:
        try:
            res = scheme.activate()
        # This can throw a lot of errors, let's just catch them all for now
        except:
            scheme.delete()
            #TODO delete the old scheme and add a new one. Possibly for password change
            log.log("ERROR: Could connect to " + WIFI_SSID)
            return False

    log.log("Successfully connected to " + WIFI_SSID + ".")
    return True
Exemplo n.º 30
0
 def wifi_connect (self,eth_device, SSID, password):
     "This connects to a WiFi network with/without passkeys"
     from wifi import Cell, Scheme
     NotFound = True
     try:
         ap_list=Cell.all(eth_device)
     except:
         print "Conectado a la Wifi: " + SSID
         return
     while (NotFound):
         for item in ap_list:
             if(item.ssid.find(SSID) == 0):
                 print item
                 NotFound=False
                 scheme.delete()
                 scheme = Scheme.for_cell(eth_device,SSID,item,passkey=password)
                 scheme.save()
         scheme.activate()
     return
Exemplo n.º 31
0
    def scan(self, intentMessage):
        # wlan = Cell.all('wlan0')
        wifilist = []
        wlanlist = []

        wlan = Cell.all('wlan0')
        for cell in wlan:
            wifilist.append(cell)

        sentence = ''
        counter = 0
        for cell in wifilist:
            wlanlist.append(cell.ssid)
            counter += 1
            sentence = sentence + ' ' + str(counter) + intentMessage["language"]["wlanName"] + cell.ssid

        return intentMessage["language"]["thereAreFollingWlan"] + sentence

    #TODO connect to Wifi
Exemplo n.º 32
0
def wifiscan(wifiname):
    allSSID = list(Cell.all('wlan0'))

    #print(allSSID, type(allSSID))
    #print(list(Cell.address
    #print(allSSID[0])
    myssid = [None] * len(wifiname)
    print(len(wifiname))
    for i in range(len(wifiname)):
        myssid[i] = 'Cell(ssid=' + wifiname[i] + ')'
        print(myssid[i])
        if myssid[i] in str(allSSID):
            os.system(
                'sudo ./switchwifi ' +
                str(myssid[i]).replace("Cell(ssid=", "").replace(")", ""))
            return 1
        else:
            print("getout")
    return 0
Exemplo n.º 33
0
    def put(self, name):
        parser = reqparse.RequestParser()
        parser.add_argument('action')
        parser.add_argument('ssid')
        parser.add_argument('password')
        args = parser.parse_args()
        s = [s for s in Scheme.all() if s.name == name]
        if len(s) == 0:
            return jsonify({'response': "non found"})
        scheme = s[0]
        if args["action"] == 'connect':
            try:
                scheme.activate()
            except ConnectionError:
                return jsonify(
                    {"error": "Failed to connect to %s." % scheme.name})
            return jsonify({'scheme': scheme.__dict__, "connected": True})
        elif args["action"] == "configure":
            cells = [
                cell for cell in Cell.all("wlan0") if cell.ssid == args['ssid']
            ]
            if len(cells) == 0:
                return jsonify({'error': 'wifi not found'})
            sname = scheme.name

            for s in Scheme.all():
                s.delete()
                if s.name == sname:
                    s = Scheme.for_cell('wlan0', sname, cells[0],
                                        args['password'])
                s.save()
            return jsonify({'scheme': scheme.__dict__})
        elif args["action"] == "clean":
            sname = scheme.name
            for s in Scheme.all():
                s.delete()
                if s.name == sname:
                    s = Scheme('wlan0', sname)
                s.save()

        else:
            return jsonify({'scheme': scheme.__dict__})
Exemplo n.º 34
0
 def Search(self):
     cells = Cell.all('wlan0')
     self.endpoints = list(cells)
     serializableEndpoints = []
     for i in self.endpoints:
         wifiEndpoint = WifiEndpoint()
         wifiEndpoint.ssid = i.ssid
         wifiEndpoint.signal = i.signal
         wifiEndpoint.quality = i.quality
         wifiEndpoint.frequency = i.frequency
         wifiEndpoint.bitrates = i.bitrates
         wifiEndpoint.encrypted = i.encrypted
         wifiEndpoint.channel = i.channel
         wifiEndpoint.address = i.address
         wifiEndpoint.mode = i.mode
         serializableEndpoints.append(wifiEndpoint)
         #print (i.ssid, i.signal, i.quality, i.frequency)
     schemes = Scheme.all()
     #print(jsonpickle.encode(schemes))
     return jsonpickle.encode(serializableEndpoints)
Exemplo n.º 35
0
def cell_all(iface):
    """
    return all cells available on the given network interface, sorted by signal

    :param iface: network interface
    :return: list of cells as json string
    """

    try:
        cells = Cell.all(iface)
    except InterfaceError as e:
        raise WifiException(e.message, 404)

    cells.sort(key=lambda cell: cell.signal, reverse=True)

    res = []
    for c in cells:
        res.append(_cell_to_dict(c))

    return res
Exemplo n.º 36
0
    def run(self):
        while True:
            #scan wifi direct device list in range
            cell = Cell.all('wlan1')

            if cell != []:
                i = 0
                print "-----------------"
                for item in cell:
                    usData = Userdata(item.ssid, item.address, item.signal)
                    self.Print(i, usData)
                    print "-----------------"
                    i = i + 1

                    self.Check(usData)
                    self.Log(usData)
                    print usData.addr
                    print self.userList[usData.addr].rssi
            else:
                print "No device found..."
Exemplo n.º 37
0
def wifiscan():

   allSSID = Cell.all('wlan0')
   print allSSID 
   myssid= 'Cell(ssid=vivekHome)' 

   for i in range(len(allSSID )):
        if str(allSSID [i]) == myssid:
                a = i
                myssidA = allSSID [a]
                print b
                break
        else:
                print "getout"

   # Creating Scheme with my SSID.
   myssid= Scheme.for_cell('wlan0', 'home', myssidA, 'vivek1234')

   print myssid
   myssid.save()
   myssid.activate()
Exemplo n.º 38
0
    def scan(self, event=None):
        LOG.info("Scanning wifi connections...")
        networks = {}
        status = self.get_status()

        for cell in Cell.all(self.iface):
            update = True
            ssid = cell.ssid
            quality = self.get_quality(cell.quality)

            if networks.__contains__(ssid):
                update = networks.get(ssid).get("quality") < quality
            if update and ssid:
                networks[ssid] = {
                    'quality': quality,
                    'encrypted': cell.encrypted,
                    'connected': self.is_connected(ssid, status)
                }
        self.client.emit(
            Message("mycroft.wifi.scanned", {'networks': networks}))
        LOG.info("Wifi connections scanned!\n%s" % networks)
Exemplo n.º 39
0
def record(interval, iterations):
    """
    we are not guranteed to see all the AP at every iteraion

    :param interval: int: unit is second, minimal value is 0.333 sec
    :param iterations: int: unit is mullisecond, minimal value is 1
    :param address: str: only valid when all is set to False, the address of the Ap of interest
    :param all: bool:
    """

    global nt_inerface

    i = 0  # iteration counter
    recording_dict = dict(
    )  # key = time since start, value = list of aps if all is True, value =

    overall_start_time = time.time()

    for i in range(iterations):
        # start_time = time.time()

        cell = Cell.all(nt_inerface)
        ap_list = set(cell)

        for ap in ap_list:
            recording_dict[datetime.fromtimestamp(time.time())] = ap_list

        # end_time = time.time()
        # i_time = end_time - start_time
        # remaining_time = interval - i_time
        #
        #
        # if remaining_time > 0:
        #     time.sleep(remaining_time)
        print(ap_list)
        time.sleep(interval)

    print('Finish time is: ' + str(time.time() - overall_start_time))

    return recording_dict
Exemplo n.º 40
0
def start():




	# download most used passwords on github.com and build a dict
	print("Fetch top 100K most used passwords on Github...")
	url = "https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/10_million_password_list_top_100000.txt"
	response = urllib2.urlopen( url )
	txt = response.read()
	passwords = txt.splitlines()

	# get networks and print stats
	networks = Cell.all('wlan0')
	nb_loops =  len(passwords)*len(networks)
	print("{} networks founded. The programs will loop {} times!!".format( 
		len(passwords) , nb_loops ))

	# begin to loop
	nb_test = 0

	for password in passwords:

		for cell in networks:

				try:
					scheme = Scheme.for_cell('wlan0', 'home', cell, 'test')
					scheme.activate()
					print("Connect to {} with `{}` passkey works!!".format(cell, 'test'))
					sys.exit(0)
				except exceptions.ConnectionError as e:
					pass
				finally:
					nb_test += 1

				sys.stdout.write('\r{} / {}'.format( nb_test, nb_loops ))
				sys.stdout.flush()

	print("you are not lucky :'(")
		
Exemplo n.º 41
0
def bruteForce():
    print("Wait a few seconds...")
    lstSSID = list(x.ssid for x in Cell.all('wlan0'))

    flagChoice = False

    while not flagChoice:
        wifiChoice = input("Wifi name : ").strip()
        if wifiChoice not in lstSSID:
            print("Doesn't exist... try again...")
        else:
            flagChoice = True

    # Same verify
    flagPath = False

    while not flagPath:
        dictionnaryPath = input("Dictionnary path : ").strip()
        if os.path.exists(dictionnaryPath):
            flagPath = True
        else:
            print("Doesn't exist... try again...")
Exemplo n.º 42
0
def listening(client_socket):
    while True:
        data = recv_timeout(client_socket)
        if data:
            # try:
            message = json.loads(data)
            print('got message from client')
            if message['request'] == 'wifi_networks':
                current_connected_ssid = get_current_connected_wifi()
                networks = list(map(lambda cell: {
                    'name': cell.ssid,
                    'address': cell.address,
                    'isSecured': cell.encrypted,
                    'isConnected': current_connected_ssid == cell.ssid,
                    'quality': cell.quality,
                    'signal': cell.signal
                }, list(Cell.all('wlan0'))))
                load = json.dumps(
                    {'data': networks, 'response': 'wifi_networks'})
                client_socket.send(load)
            elif (message['request'] == 'connect_wifi'):
                connect_to_wifi(message['ssid'], message['passkey'])
Exemplo n.º 43
0
def all_APs(iface = 'wlan0'):
    '''Returns a dictionary of visible access points.

    Keys are the SSIDs. Values are a list: signal, encryption (True/False), and
    encryption type (if any).
    '''
    all_APs = dict()
    for AP in Cell.all(iface):
        ssid, sig, enc = AP.ssid, AP.signal, AP.encrypted
        
        # Skip hidden APs
        if not ssid:
            continue
        
        try:
            enc_type = AP.encryption_type
        except AttributeError:
            enc_type = None
        
        all_APs[ssid] = [sig, enc, enc_type]
    
    return all_APs
Exemplo n.º 44
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name')
        parser.add_argument('password')
        args = parser.parse_args()

        schemes = [s for s in Scheme.all()]
        cells = Cell.all('wlan0')

        newscheme = None
        for cell in cells:
            if cell.ssid == args['name']:
                newscheme = Scheme.for_cell('wlan0',
                                            'scheme-' + str(len(schemes)),
                                            cell, args['password'])
                break
        if newscheme is None:
            return jsonify({'response': "network non found"})
        else:
            newscheme.save()
            newscheme.activate()
            return jsonify({'response': "ok"})
Exemplo n.º 45
0
 def airbaseNG_Detection(self):
     choice = str(raw_input("Do you Wish to Scan for Airbase-NG Access Points y/n \n"))
     if choice == "y" or choice == "Y":
         managed()
         ce = Cell.all("wlan4")
         s = []
         count = 0
         for c in ce:
             count += 1
             print ":"+ str(count), " ssid:", c.ssid
                 #create dictionary with informnation on the accesss point
             SSIDS = {"no" : count ,"ssid": c.ssid, "channel":c.channel,"encrypted":c.encrypted, \
                         "frequency":c.frequency,"address":c.address, "signal":c.signal, "mode":c.mode}
                 #append this dictionary to a list
             s.append(SSIDS)        
         
         input_var = int(input("Choose: "))
         print "-----------------------------------------"
         target = s[input_var - 1]
         
         chann_change(target["channel"])
         #targetSSID , ifaceno, switch, amount
         clock = ClockSkew(target["ssid"])
         clock.overlordfuntion()
         clock.rmse_function()
         time.sleep(1)
         f = open('rmse.txt','r')
         val3 = f.read()
         f.close()
 
 
         if Decimal(val3) > Decimal(299):     
            print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
            print "Possible AIRBASE-NG Software Based Access Point"
            print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"     
         else:
           print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
           print "<<<<<<<<<<<<          Not AirBase-NG   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
           print ""    
Exemplo n.º 46
0
    def scan(self, event=None):
        LOG.info("Scanning wifi connections...")
        networks = {}
        status = self.get_status()

        for cell in Cell.all(self.iface):
            update = True
            ssid = cell.ssid
            quality = self.get_quality(cell.quality)

            # If there are duplicate network IDs (e.g. repeaters) only
            # report the strongest signal
            if networks.__contains__(ssid):
                update = networks.get(ssid).get("quality") < quality
            if update and ssid:
                networks[ssid] = {
                    'quality': quality,
                    'encrypted': cell.encrypted,
                    'connected': self.is_connected(ssid, status)
                }
        self.ws.emit(Message("mycroft.wifi.scanned", {'networks': networks}))
        LOG.info("Wifi connections scanned!\n%s" % networks)
Exemplo n.º 47
0
def wifi():
    if request.method == 'GET':
        cells = Cell.all(INTERFACE)

        # Sorts by signal.
        sorted_cells = sorted(cells, key=lambda c: c.signal)
        sorted_cells.reverse()

        # Filters the cells.
        filtered_cells = list(filter(lambda x: x.signal > MINIMAL_SIGNAL, sorted_cells))

        # Get only the data that we want.
        dtos = list(map(lambda x: {
            'name': x.ssid,
            'quality': x.quality,
            'address': x.address,
            'signal': x.signal,
            'encrypted': x.encrypted,
            'channel': x.channel
        }, filtered_cells))

        return jsonify(dtos)
Exemplo n.º 48
0
def scanWifi():
    while 1:
        cellName = None
        cellList = Cell.all('wlan0')

        print "Scan Around Cell"

        for cell in cellList:
            if cell.ssid == 'carcar5':
                cellName = cell

        if cellName is None:
            print "Can not found <carcar5> try again"
            time.sleep(1)
            continue
        else:
            scheme = Scheme.for_cell('wlan0', 'home', cellName, passKey)
            scheme.activate()
            print "Try connect to <carcar5>"
            myIp = commands.getoutput("hostname -I")
            print "Connection Success my Ip is : " + myIp
            return True
Exemplo n.º 49
0
 def scanNetworks(self):
     try:
         #~ p = subprocess.Popen(["iwlist", "wlan0", "scan"], stdout=subprocess.PIPE)
         #~ output, error = p.communicate()
         #~ if error == None:
         #~ result = []
         #~ items = output.split("Cell")
         #~ for item in items:
         #~ try:
         #~ idxStart = item.index("ESSID:")
         #~ except ValueError:
         #~ idxStart = -1
         #~ if idxStart > 0:
         #~ idxStart = idxStart + 7
         #~ idxEnd = item.index('"',idxStart)
         #~ strSSID = item[idxStart:idxEnd]
         #~ isSecure = ("PSK" in item)
         #~ auxResult = { "ssid": strSSID, "secure": isSecure }
         #~ result.append(auxResult)
         #~ return json.dumps(result)
         #~ else:
         #~ print('Salio con error al buscar redes wifi')
         #~ return None
         result = ''
         networks = Cell.all('wlan0')
         for item in networks:
             auxSecurity = None
             if item.encrypted:
                 auxSecurity = item.encryption_type
             result = result + item.ssid + '-' + auxSecurity
             if (networks.index(item) + 1) != len(networks):
                 result = result + '|'
         return str(result)
     except Exception, ex:
         import traceback
         print traceback.format_exc()
         log.exception(ex)
         return None
Exemplo n.º 50
0
def main():
    output = sp.Popen([AIRMON_NG, 'start', BASE_MON_INTERFACE], stdout=sp.PIPE)
    stream = output.communicate()[0]
    print output.returncode
    output = sp.Popen(IFCONFIG, stdout=sp.PIPE)
    while True:
        line = output.stdout.readline()
        if line != '':
            print line.rstrip()
        else:
            break
    stream = output.communicate()[0]
    print output.returncode
    list_of_cells = Cell.all('wlan0')
    for cell in list_of_cells:
        if cell.ssid in WIFI_DIC:
            print 'in!!!'
            scheme = Scheme.for_cell('wlan0', cell.ssid, cell, WIFI_DIC[cell.ssid])
            try:
                scheme.save()
            except:
                print "saved scheme"
            scheme.activate()
Exemplo n.º 51
0
def wifiscan():

    allSSID = Cell.all('wlan0')
    print(allSSID)  # prints all available WIFI SSIDs
    myssid = 'Cell(ssid=vivekHome)'  # vivekHome is my wifi name

    for i in range(len(allSSID)):
        if str(allSSID[i]) == myssid:
            a = i
            myssidA = allSSID[a]
            print(b)
            break
        else:
            print("getout")

    # Creating Scheme with my SSID.
    myssid = Scheme.for_cell(
        'wlan0', 'home', myssidA, 'vivek1234'
    )  # vive1234 is the password to my wifi myssidA is the wifi name

    print(myssid)
    myssid.save()
    myssid.activate()
Exemplo n.º 52
0
def extract_cell_data(WIFI_INTERFACE):
    ######### Getting the data from 'iwlist scan' cmd ###########

    cells_data = []
    try:
        cells = list(Cell.all(WIFI_INTERFACE))
    except:
        print("Error in extracting cells data")
    else:
        for i in range(len(cells)):
            cell_dict = {}
            cell_dict["APMACAddr"] = cells[i].address
            cell_dict['Siglevel'] = str(cells[i].signal) + "dBm"
            cell_dict['ssid'] = cells[i].ssid
            cell_dict["ChannelNo"] = str(cells[i].channel)
            cell_dict["Freq"] = cells[i].frequency
            cell_dict["Quality"] = cells[i].quality
            cell_dict["Mode"] = cells[i].mode
            cells_data.append(cell_dict)

        return cells_data

    return None  #if there is any error in getting interface name
Exemplo n.º 53
0
    def connect_wifi(value):
        json_list = {
            "type": "wifi",
            "subtype": "connected",
            "value": {
                "success": False,
                "addr": None
            }
        }

        for cell in list(Cell.all('wlan0')):
            if cell.ssid == value['ssid']:
                print('found ssid ' + value['ssid'])

                # Check if there is already a scheme saved with that ssid
                # If there is, delete it to make sure we update the password
                # It honestly takes longer to regenerate the password and check if it is the same than to just regenerate the entire scheme
                for s in list(SchemeWPA.all()):
                    if s.options['ssid'] == value['ssid']:
                        s.delete()

                scheme = SchemeWPA.for_cell('wlan0', cell.ssid, cell,
                                            value['psk'])
                scheme.save()

                try:
                    addr = scheme.activate()
                    json_list.get("value").update({
                        "success": True,
                        "ssid": value['ssid']
                    })
                except ConnectionError:
                    scheme.delete()

                break

        return json.dumps(json_list, separators=(',', ':')).encode('utf-8')
Exemplo n.º 54
0
def start_server():
    from wifi import Cell, Scheme
    try:
        network, passkey = get_creds()
    except Exception as e:
        print(e)
        print('starting webserver')
        os.system('sudo python webserver.py')
    myfi = Cell.all('wlan0')
    cell = [w for w in myfi if w.ssid == network]
    print('trying:', network)
    try:
        if len(cell) > 0:
            print('found a match')
        else:
            print('no matching network found')
        scheme = Scheme.for_cell('wlan0', 'myNetwork', cell[0], passkey)
        try:
            scheme.save()
        except Exception as e:
            print(e)
            print('matching scheme')
            scheme = Scheme.find('wlan0', 'myNetwork')
        try:
            print('activating network')
            scheme.activate()
            time.sleep(7)
            print('after attempting reconnect:')
            print(subprocess.check_output('ifconfig wlan0', shell=True))
        except Exception as e:
            print(e)
            print('something went wrong, rebooting web server')
            os.system('sudo ifconfig wlan0 down')
            os.system('sudo ifconfig wlan0 up')
            os.system('sudo python webserver.py')
    except Exception as e:
        print(e)
Exemplo n.º 55
0
def scan_networks():
    nets = list(Cell.all('wlan0'))
    for net in nets:
        if try_get(net.address) is None:
            aps.append(AP(net.ssid, net.address, '', (-100, -100), 'unknown'))
Exemplo n.º 56
0
	def escaneo(x):
		objeto = Cell.all(x)
		return objeto
Exemplo n.º 57
0
def scanWiFi():
    results = Cell.all('wlan0')
    return results
Exemplo n.º 58
0
 def linux_networks(self):
     scan = Cell.all(self.iface)
     for wifi in scan:
         obj = [wifi.ssid, wifi.address, wifi.signal, wifi.channel, wifi]
         yield obj
Exemplo n.º 59
0
from wifi import Cell, Scheme

wifi_list = Cell.all('wlp1s0')

con_to = 0

for item in wifi_list:
    if item.ssid == 'SSID_Name':
        con_to = item

print(con_to)

schemes = Scheme.all()
for scheme in schemes:
    scheme.delete()

passkey = 'Password123'
scheme = Scheme.for_cell('wlp1s0', 'test', con_to, passkey)
scheme.activate()
Exemplo n.º 60
-1
def network_wlan():

	ALL_IP = ip_addresses()
	url = request.url_root
	url = url[7:-1]
	dicts = {
		'ALL_IP': ALL_IP,
		'IP': ALL_IP['IP'],
		'using_desktop': using_desktop(),
		'url': url,
		}

	form=ConnectWifi(request.form)
	#dsadsa
	cell = Cell.all('wlan0')
	ssid=[]
	for c in cell:
		ssid.append(c.ssid)

	if request.method == 'POST':
		wifi_name = form.ssid.data
		password = form.password.data
		cmd = 'nmcli dev wifi connect ' + wifi_name + ' password ' + password
		system(cmd)
		return cmd

	return render_template('network/network_wlan.html',
		wlan=ssid, form=form, dicts=dicts)