Пример #1
0
    def scan_network(self):
        if self.os == "linux" or self.os == "linux2":
           scanner = self.linux_networks()
        elif self.os == "darwin":
           scanner = self.osx_networks()
        #elif os == "win32":
            
        results = []
        for wifi in scanner:
            if self.verbosity > 1:
                print(wifi)

            # match NET's default SSID
            if self.regex.search(wifi[0]) is not None:
                print("Found WIFI!")
                # the password consists of CM_MAC last 4 hexas of the router,
                # which are the third hexa of the BSSID
                # plus the last 3 hexas of the SSID

                chunks = [
                    ''.join(wifi[1].upper().split(":")[2:3]),
                    wifi[0].split("_")[1][2:]
                ]

                password = ''.join(chunks)
                results.append([wifi[0], password, wifi[1]])

                if self.os != 'darwin':
                    Scheme.for_cell(
                        self.iface, wifi[1], wifi[4], password
                    ).save()

        return results
Пример #2
0
 def connect(self):
     message = None
     error = False
     cell = None
     if self.ssid != "":
         for i, v in enumerate(self.cells):
             if v.ssid == self.ssid:
                 cell = self.cells[i]
                 break
     if cell:
         scheme = None
         if cell.encrypted:
             if self.password != "":
                 scheme = Scheme.for_cell(self.interface, "home", cell, passkey=self.password)
         else:
             scheme = Scheme.for_cell(self.interface, "home", cell)
         if scheme:
             try:
                 scheme.delete()
                 scheme.save()
                 try:
                     scheme.activate()
                     message = "OK"
                     error = False
                 except Exception, e:
                     message = e
                     error = True
             except Exception, e:
                 message = e
                 error = True
Пример #3
0
 def connect(self):
     message = None
     error = False
     cell = None
     if self.ssid != "":
         for i, v in enumerate(self.cells):
             if v.ssid == self.ssid:
                 cell = self.cells[i]
                 break
     if cell:
         scheme = None
         if cell.encrypted:
             if self.password != "":
                 scheme = Scheme.for_cell(self.interface, "home", cell, passkey=self.password)
         else:
             scheme = Scheme.for_cell(self.interface, "home", cell)
         if scheme:
             try:
                 scheme.delete()
                 scheme.save()
                 try:
                     scheme.activate()
                     message = "OK"
                     error = False
                 except Exception, e:
                     message = e
                     error = True
             except Exception, e:
                 message = e
                 error = True
Пример #4
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)
Пример #5
0
def connecct(ssid, passkey = None):
    for cell in Cell.all('wlan0'):
        if cell.ssid == ssid:
            print('found {}'.format(ssid))
            connect_cell = cell

    if (passkey == None):
        s = Scheme.for_cell('wlan0', 'home', connect_cell)
    else:
        s = Scheme.for_cell('wlan0', 'home', connect_cell, passkey)
    s.save()
    s.activate()
    s.delete()
    return s
Пример #6
0
	def run(self):
		while(self.__continue):
			strs = serial_read_line()
			print (strs)
			if(strs == "REQ?CON"):
				serial_send_line("RSP?CON")
				print("respond")
			elif(strs == "GET?SSIDLIST"):
				ssids = get_wifi_ssid(self.__cell)
				serial_send_line("RSP?SSID")
				serial_send_line(str(len(ssids)))
				for ssid in ssids:
					serial_send_line(ssid)
				
			elif(strs == "SET?SSID"):
				print("SET SSID")
				ssid = int(serial_read_line())
				pswd = serial_read_line()
				print(ssid, self.__cell[ssid])
				scheme = Scheme.for_cell('wlan0','home',self.__cell[ssid],pswd)
				try:
					scheme.delete()
				except:
					pass
				try:
					scheme.save()
				except:
					pass
				try:
					scheme.activate()
					serial_send_line("RSP?COMP")
				except:
					serial_send_line("RSP?SSID")
Пример #7
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 :
			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
Пример #8
0
    def run(self):
        while (self.__continue):
            strs = serial_read_line()
            print(strs)
            if (strs == "REQ?CON"):
                serial_send_line("RSP?CON")
                print("respond")
            elif (strs == "GET?SSIDLIST"):
                ssids = get_wifi_ssid(self.__cell)
                serial_send_line("RSP?SSID")
                serial_send_line(str(len(ssids)))
                for ssid in ssids:
                    serial_send_line(ssid)

            elif (strs == "SET?SSID"):
                print("SET SSID")
                ssid = int(serial_read_line())
                pswd = serial_read_line()
                print(ssid, self.__cell[ssid])
                scheme = Scheme.for_cell('wlan0', 'home', self.__cell[ssid],
                                         pswd)
                try:
                    scheme.delete()
                except:
                    pass
                try:
                    scheme.save()
                except:
                    pass
                try:
                    scheme.activate()
                    serial_send_line("RSP?COMP")
                except:
                    serial_send_line("RSP?SSID")
Пример #9
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()
Пример #10
0
def wifi():
    error = None
    if request.method == 'GET':
        return render_template('wifi.html', error=error)
    if request.method == 'POST':
        if request.form['wifi-name'] and request.form['wifi-key']:
            try:
                cell = searchCell(request.form['wifi-name'])
                if cell:
                    scheme = Scheme.for_cell(wifiInterface,
                                             request.form['wifi-name'], cell,
                                             request.form['wifi-key'])
                    scheme.save()
                    scheme.activate()
                else:
                    error = 'Le wifi n\'a pas été trouvé veuillez en renseigner un autre'
                    return render_template('wifi.html', error=error)
            except ConnectionError:
                error = 'Impossible de se connecter au réseau veuillez renseigner des informations valides'
                return render_template('wifi.html', error=error)
            file = open('.known_wifi', 'a')
            file.write(request.form['wifi-name'] + '\n')
            file.close()
            return redirect(url_for('ip'))
        else:
            error = 'Vous devez remplir les deux champs du formulaire'
            return render_template('wifi.html', error=error)
Пример #11
0
 def save_network(self, network_ssid, password):
     network = self.get_network(network_ssid)
     saved_networks = self.get_saved_networks()
     saved_networks_count = len(saved_networks)
     new_network = Scheme.for_cell(self.interface,
                                   'network_' + str(saved_networks_count),
                                   network, password)
     new_network.save()
Пример #12
0
def wifiscan():
	Cell.all('wlan0')
	allSSID = list(Cell.all("wlan0"))[0]
	myssid = Scheme.for_cell('wlan0','home',allSSID,target_pwd)
	myssid.activate()
	
	myssid = Scheme.find('wlan0','home')
	myssid.activate()
Пример #13
0
 def join_network(self, data):
     cell = [x for x in self.networks if x.ssid == data['name']][0]
     conn = Scheme.for_cell(self.interface, data['name'], cell, data['passkey'])
     self.wifiserver.svc.apmode = False
     while self.wifiserver.svc.ap_active:
         logging.debug("Waiting for AP to shut down")
         sleep(1)
     logging.debug("Activating Wireless connection")
     conn.activate()
     return {'join': 'successful'}  # FIXME: return something more meaningful
Пример #14
0
 def connect(interface, password, ssid):
     if Utils.is_saved(interface, ssid):
         Scheme.find(interface, ssid).activate()
         return True
     c = Utils.get_cell(ssid, interface)
     if c is None:
         return False
     s = Scheme.for_cell(interface, ssid, c, password)
     s.save()
     s.activate()
     return True
Пример #15
0
def connect_to_network(ssid, passkey=""):
    """ Try to connect to the given wifi network """
    if ARGS.verbose >= 1: print "Connect to %s with passKey '%s'" % (ssid, passkey)
    try:
        cells = Cell.all('wlan1')
    except:
        print "Error connecting to wifi; is iwlist available on your machine?"

    for cell in cells:
        print "CHECK %s with %s" % (cell.ssid, ssid)
        if cell.ssid == ssid:
            print "Selected nework found, connecting."
            if passkey != "":
                scheme = Scheme.for_cell('wlan1', ssid, cell, passkey)
            else:
                scheme = Scheme.for_cell('wlan1', ssid, cell)
            scheme.save()
            scheme.activate()
        return
    if ARGS.verbose >= 1: print "Not able to find the selected network."
Пример #16
0
def connectToNetwork(device: Device, val, args):
    cell = args[0]
    if cell.encrypted:
        device.dispError(["Enter Password"])
        password = device.dispKeyboard()
    else:
        password = None

    scheme = Scheme.for_cell("wlan0", cell.ssid, cell, password)
    with open("/home/pi/opc/network.pkl", "wb") as f:
        pickle.dump(scheme, f)
    p = call(["sudo", "/home/pi/opc/connectToNetwork.sh"])
Пример #17
0
	def connect_wifi(self, wifi_id, passkey):
		print "Adding new Wifi"
		current_cell = self.cell[wifi_id]
		current_ssid = self.cell[wifi_id].ssid
		print "Cell info: "
		print current_cell

		scheme = Scheme.for_cell('wlan0', self.current_ssid, self.cell, passkey)
		scheme.save()
		print "Scheme info"
		print scheme
		return scheme.activate()
Пример #18
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
            scheme.delete()
            if cell.encrypted is True:
                scheme = Scheme.for_cell('wlan0', sname, cells[0], args['password'])
            else:
                scheme = Scheme.for_cell('wlan0', sname, cells[0])
            scheme.save()
            return jsonify({'scheme': scheme.__dict__})

        elif args["action"] == "clean":
            sname = scheme.name
            for s in Scheme.all():
                if s.name == sname:
                    s = Scheme('wlan0', sname)
                    scheme.delete()
                    s.save()
        else:
            return jsonify({'scheme': scheme.__dict__})
Пример #19
0
def connect(ssid, passkey):
    wifi_list = Cell.all('wlan0')
    wifi_to_connect = None
    for cell in wifi_list:
        if (cell.ssid == ssid):
            wifi_to_connect = cell

    if (wifi_to_connect == None):
        return False

    scheme = Scheme.for_cell('wlan', 'home', wifi_to_connect, passkey)
    scheme.save()
    scheme.activate()
    return True
Пример #20
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']:
                if cell.encrypted is True:
                    newscheme = Scheme.for_cell('wlan0', 'scheme-'+str(len(schemes)), cell, args['password'])
                else:
                    newscheme = Scheme.for_cell('wlan0', 'scheme-'+str(len(schemes)), cell)
                break
        if newscheme is None:
            return jsonify({'response': "network non found"})
        else:
            newscheme.save()
            newscheme.activate()
            return jsonify({'response': "ok"})
Пример #21
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
Пример #22
0
def connect_to_wifi(interface, name, cell, password):
    scheme = Scheme.for_cell(interface, name, cell, password)
    previous_scheme = Scheme.find(interface, name)
    if previous_scheme is not None:
        previous_scheme.delete()

    print scheme
    if scheme.find(interface, cell) is None:
        scheme.save()

    try:
        scheme.activate()
    except subprocess.CalledProcessError, e:
        print "Error: ", e.output
        return False
def scanWifi():
	while 1:	
		cellName=None
		#Wifi scannig use interface 'wlan0'
		cellList = Cell.all(iface)


		print "Network::scanWifi: Scan Around Cell"
		
		#find in cellList 
		for cell in cellList:
			if cell.ssid == ssid:
				cellName =cell


		if cellName is None:
			print "Network::scanWifi: Can not found <carcar5> try again"
			time.sleep(1)
			continue

		# if there is 'carcar5' ap 
		# Make connection 
		else :
			temp = Scheme.find(iface,nickname)
			if temp is not None:
				temp.delete()

			scheme = Scheme.for_cell(iface,nickname,cellName, passKey)
			scheme.save()
			scheme.activate()
				
			print "Network::scanWifi: Try connect to <carcar5>"
			myIp = commands.getoutput("hostname -I")
			print "Network::scanWifi: Connection Success my Ip(" + myIp + ")"

			childPid = os.fork()
			#print "after os.fork() " + str(pid)
			#print str(os.getpid()) + "--> child Pid : " + str(childPid)
			# Parent process : Send Data	
			if childPid:
				#print "Parent PID : " + str(os.getpid()) + " , Child PID : "+ str(childPid)
				sendData(childPid)


			# Child process : Receive Data
			else :
				#print "Child PID : " + str(os.getpid()) + " Parent PID : " + str(os.getppid())	
				receiveData()
Пример #24
0
def connectToWifi(ssid, passd):
    try:
        for elm in WlanCell:
            if elm.ssid == ssid:
                tmp = Scheme.find('wlan0', ssid)
                if tmp is not None:
                    tmp.delete()
                scheme = Scheme.for_cell('wlan0', ssid, elm, passd)
                scheme.save()
                scheme.activate()
            print("Connected To Wifi " + ssid)
            return True
        return False
    except Exception:
        print("Error by Connecting with " + ssid)
        return False
Пример #25
0
def hubconnection4(request):
	try:
		curPassword =  request.GET['password']
		curCell = []
		for cell in Cell.all('wlan1'):
			if cell.ssid == curSSID:
				curCell = cell
		scheme = Scheme.for_cell('wlan1', curSSID, curCell, curPassword)
		scheme.activate()
	except:
		curPassword = []
	context = {
		'curSSID' : curSSID,
		'curPassword' : curPassword,
	}
	return render(request, 'she/hubconnection4.html', context)
Пример #26
0
 def Setup(self, ssid, password):
     cell = None
     for i in self.endpoints:
         if i.ssid == ssid:
             cell = i
             break
     if cell is None:
         cell = Cell.from_string(ssid)
         if cell is None:
             #print('failure')
             return False
     scheme = Scheme.for_cell(self.interface, ssid, cell, password)
     scheme.save()
     scheme.activate()
     scheme.autoreconnect()
     #print('success')
     return True
Пример #27
0
def connect(interface, found_aps, selected_ap):
    #access_points = Cell.all(interface)
    found_aps = Cell.all(interface)
    print("In connect_linux.connect\n")
    #print(list(found_aps))
    for ap in found_aps:
        print("Checking " + ap.ssid)
        if ap.ssid == selected_ap:
            print("MATCH")
            print("Trying to connect to " + ap.ssid)
            scheme = Scheme.for_cell(interface, 'net', ap)
            results = scheme.activate()
            print(results)

        print("Check done.\n")

    print("For-loop ended.\n")
Пример #28
0
def connectTo(ap, interface):
	try:
		scheme = Scheme.for_cell(interface, ap.ssid, ap)
		scheme.delete() #otherwise "This scheme already exists" error
		scheme.save()
		scheme.activate() #connect to the Parrot's wifi
	except Exception as detail:
		logging.error("Error while trying to connect to wifi in function connectTo - %s", detail)
		return False
	#reset global variables for sniffing
	global srcMAC, dstMAC, srcIP, dstIP, seqNr
	srcMAC = ""
	dstMAC = ""
	srcIP = ""
	dstIP = ""
	seqNr = ""
	return True
Пример #29
0
def wifi(display, conf):
    if conf.get("wifi") and not get_current_wifi():
        cells = Cell.all(conf["wifi"]["interface"])
        for i in cells:
            scheme = Scheme.find(conf["wifi"]["interface"],_name(i))
            if not scheme:
                if i.ssid in conf["wifi"]["networks"]:
                    display.animateRow(0,"Preparing " + i.ssid)
                    scheme = Scheme.for_cell(
                        conf["wifi"]["interface"], _name(i),
                        i, conf["wifi"]["networks"][i.ssid])
                    scheme.save()
            if scheme:
                display.animateRow(0,"Trying " + scheme.options["wpa-ssid"])
                scheme.activate()
                return True
        return False
Пример #30
0
def connect(esid, passkey=None, intf='wlan0'):
	cells = Cell.where(intf, lambda c: c.ssid == esid);

	if len(cells) == 0:
		raise LookupError('Network was not found');

	if len(cells) > 1:
		raise LookupError('Sorry, network SSID is ambiguous');

	scheme = Scheme.for_cell(intf, STORED_SCHEME_NAME, cells[0], passkey);

	old = Scheme.find(intf, STORED_SCHEME_NAME);
	if old is not None:
		old.delete();

	scheme.save();
	scheme.activate();
Пример #31
0
def scanAndConnectToParrot(interface, whitelist): #TODO implement whitelist, TODO change to separate scan & connect
	parrotNotFound = True
	while parrotNotFound:
		aps = Cell.all(interface)
		print aps
		for ap in aps:
			if ap.address.startswith('90:03:B7') or ap.address.startswith('58:44:98:13:80'): #if it is a parrot OR my phone (for testing)
				print "Parrot Wifi found"
				print ap
				parrotNotFound = False
				scheme = Scheme.for_cell(interface, 'abcde', ap)
				scheme.delete() #otherwise "This scheme already exists" error
				scheme.save()
				scheme.activate() #connect to the Parrot's wifi
				print "Connected to Parrot Wifi"
				break
		sleep(1)
Пример #32
0
def connect(interface, found_aps, selected_ap):
    #access_points = Cell.all(interface)
    found_aps = Cell.all(interface)
    print("In connect_linux.connect\n")
    #print(list(found_aps))
    for ap in found_aps:
        print("Checking " + ap.ssid)
        if ap.ssid == selected_ap:
            print("MATCH")
            print("Trying to connect to "+ap.ssid)
            scheme = Scheme.for_cell(interface, 'net', ap)
            results = scheme.activate()
            print(results)

        print("Check done.\n")

    print("For-loop ended.\n")
Пример #33
0
	def AttemptToConnectTo(self, targetName):
		targetCell = None

		# Find network cells in range
		cells = Cell.all(WIRELESS)

		# Find targetCell based on targetName
		for cell in cells:
			if (str(cell.ssid) == targetName):
				targetCell = cell

		# Check if cell retrieval failed
		if not targetCell:
			print("Failed to find chosen network")
			return False

		# Attempt Connection
		try:
			scheme = Scheme.for_cell(WIRELESS, targetName, targetCell)
		except TypeError:
			print("Failed to connect to scheme")
			return False

		try:
			scheme.save()
		except AssertionError:
			pass
		except IOError:
			print("Failed to save scheme")
			return False

		# Attempt to activate Scheme with timeout protection
		#signal.signal(signal.SIGALRM, TimeoutHandler)
		signal.alarm(CONNECTIONTIMEOUT)

		try:
			scheme.activate()
		except IOError:
			print("Activation of connection scheme timed out!")
			return False

		signal.alarm(0)

		# Successful connection
		return True
Пример #34
0
def _save_to_file(iface, ssid, cell, passkey):
    """
    store new network scheme in /etc/network/interfaces

    :param iface: network interface
    :param ssid: network name
    :param cell: cell object matching the arguments
    :param passkey: authentication passphrase
    :return:
    """

    # check if passkey is required
    if cell.encrypted and passkey is None:
        raise WifiException("ssid {}: passkey required".format(ssid), 400)

    scheme = Scheme.for_cell(iface, ssid, cell, passkey)
    scheme.save()
    return scheme
Пример #35
0
    def connect(self, ssid, password):
        """The high-level method to try connect to one of available networks with using `wifi` library.

        Args:
            ssid (str):       	        The name of the surrounding access point.
            password (str):       	    The password of the surrounding access point.
        """
        result = False
        for cell in self.current_cells:
            if cell.ssid == ssid:
                try:
                    scheme = Scheme.for_cell(self.wlan, ssid, cell, password)
                    scheme.activate()
                    result = True
                except Exception as e:
                    print(e)

        return result
Пример #36
0
def connectTo(ap, interface):
    try:
        scheme = Scheme.for_cell(interface, ap.ssid, ap)
        scheme.delete()  #otherwise "This scheme already exists" error
        scheme.save()
        scheme.activate()  #connect to the Parrot's wifi
    except Exception as detail:
        logging.error(
            "Error while trying to connect to wifi in function connectTo - %s",
            detail)
        return False
    #reset global variables for sniffing
    global srcMAC, dstMAC, srcIP, dstIP, seqNr
    srcMAC = ""
    dstMAC = ""
    srcIP = ""
    dstIP = ""
    seqNr = ""
    return True
Пример #37
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
Пример #38
0
def connect(adapter, ssid, psk=None, quiet=False):
	if not quiet:
		print "***setting up wireless adapter***"
	signal = []

	# get a list of all the available SSIDs that match the arg ssid
	cells = Cell.where(adapter, lambda x: x.ssid == ssid)
	print cells
	if len(cells) == 0:
		if not quiet:
			print "Cannot find SSID:", ssid
		return False

	# find the SSID with the best signal strength and select it as the cell to connect to
	for c in cells:
		signal.append(c.signal)

	max_signal = max(signal)
	max_index = signal.index(max_signal)
	cell = cells[max_index]
	scheme = Scheme.for_cell(adapter, ssid, cell, passkey=psk)

	# overwrite the scheme if already in '/etc/network/interfaces'
	# save it to '/etc/network/interfaces' if not
	if Scheme.find(adapter, ssid):
		scheme.delete()
		scheme.save()
	else:
		scheme.save()

	# attempt to connect to ssid
	try:
		if not quiet:
			print 'connecting to SSID:', cell.ssid
		scheme.activate()
		if not quiet:
			print 'connection successful'
		return True
	except:
		if not quiet:
			print('connection failed')
		return False
Пример #39
0
def create_scheme(interface, ssid, passkey):
    # Save a couple SSID / passkey into Scheme object
    cell = Cell.where(interface, lambda c: c.ssid == ssid)
    # Get cell matching SSID
    if cell:
        # Delete previous duplicate
        previous = Scheme.find(interface, ssid)
        if previous:
            print "Deleting previous \"%s\" duplicate." % (ssid)
            previous.delete()
        # Instanciate Scheme for this Cell
        scheme = Scheme.for_cell(interface, ssid, cell[0], passkey)
        print "Saving WiFi scheme \"%s\"." % (ssid)
        try:
            scheme.save()
            return scheme
        except:
            print "Scheme could not be saved."
            pass
    return False
Пример #40
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()
Пример #41
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 :'(")
		
Пример #42
0
    def click(self,btn):
        global niggers
        if btn != 'Enter':
            if btn == 'Backspace':
                niggers = niggers[:-1]
            print btn
            niggers += btn
            try:
                niggers = niggers.split("Backspace")[0]
            except:
                pass
        self.entryVariable.set(niggers)

        if btn == 'Enter':
            #
            #add pw to wifi cell scheme
            #
            self.scheme = Scheme.for_cell(str(args.interface), self.value, self.selected_cell, niggers)
            self.scheme.save()
            self.scheme.activate()
            print "Password entered: %s" % niggers
            niggers = ""
Пример #43
0
Файл: main.py Проект: drwonky/NC
    def validate_pw(self, obj):
        self.popup.dismiss()
        scheme = Scheme.find(self.wifi_iface, self.ap.ssid)

        if scheme != None:
            scheme.delete()
            print('scheme found, deleting')

        scheme = Scheme.for_cell(self.wifi_iface, self.ap.ssid, self.ap,
                                 obj.text)
        scheme.save()

        progressbar = ProgressBar(max=10)
        progress = Popup(title='Connecting...',
                         size_hint=(None, None),
                         size=(400, 100),
                         content=progressbar)
        progress.open()

        activatethread = Thread(target=self.activate_thread, args=(scheme, ))
        activatethread.start()
        print('thread started')

        while self.activation_status is None:
            time.sleep(1)
            progressbar.value = (progressbar.value + 1) % 10
            print('tick')

        progress.dismiss()

        if self.activation_status:
            self.save_ap()
            print('activated')
        else:
            scheme.delete()
            self.ask_pass()
            print('failed, asking again')
        pass
Пример #44
0
import subprocess
from wifi import Cell, Scheme
#from collections import defaultdict
cell = Cell.all('wlan0')[0]
scheme = Scheme.for_cell('wlan0', 'home', cell)
#scheme.save()
scheme.activate()
#command=['iwlist', 'wlan0', 'scan']
#output=subprocess.Popen(command, stdout=subprocess.PIPE).stdout.readlines()
#data=[]
#wifiFile=open("wifiReport.txt", "w+")
#keys=["Quality", "Encryption", "SSID"]
#networks=defaultdict(list)
#networkList=[]
#for item in output:
#   print item.strip()
#   wifiFile.write(item.strip())
#   if item.strip().startswith('ESSID:'):
#	data.append('SSID: '+item.lstrip(' ESSID:"').rstrip('"\n'))
#   if item.strip().startswith('Quality'):
#	data.append('Quality: '+item.split()[0].lstrip(' Quality=').rstrip('/70 '))
 #  if item.strip().startswith('Encryption key:off'):
#	data.append('Encryption: Open')
 #  if item.strip().startswith('Encryption key:on'):
#	data.append('Encryption: Encrypted')
#print data
#print keys
#for value in data:
#   for key in keys:
#	networks[key].append(value)
#networkList.append(dict(zip(keys, data)))
Пример #45
0
from wifi import Cell, Scheme
cell = Cell.all('wlan0')[2]
scheme = Scheme.for_cell('wlan0', 'fiBonAcci', cell, b'silentscream')
scheme.activate()
Пример #46
0
 def save_network(self, data):
     """save network to config file"""
     cell = [x for x in self.networks if x.ssid == data['name']][0]
     conn = Scheme.for_cell(self.interface, data['name'], cell, data['passkey'])
     conn.save()
     logging.info('saved network {}'.format(data['name']))
Пример #47
0
WifiName='sanjurjo'
WifiPassword='******'
WirelessETH='wlan0'
NotFound=True
from wifi import Cell, Scheme
import subprocess
subprocess.call('ifconfig ' + WirelessETH +  ' up'], shell=True)
os.system(ifconfig )
while (NotFound):
    ap_list=Cell.all(WirelessETH)
    for item in ap_list:
        if(item.ssid.find(WifiName) == 0):
            print item
            NotFound=False
            scheme.delete()
            scheme = Scheme.for_cell(WirelessETH,WifiName,item,passkey=WifiPassword)
            scheme.save()
    scheme.activate()

#We call the Upload service

subprocess.call('ifconfig ' + WirelessETH +  ' down', shell=True)
Пример #48
0
scheme = None


#Same as "sudo iwlist wlan0 scan"
cellName = None
cellList = Cell.all('wlan0')

#Find cell information which ssid is 'carcar5' 
for cell in cellList:
	if cell.ssid == 'carcar5':
		cellName = cell

#Connect to wifi
scheme = Scheme.find('wlan0','home')
if scheme is None:
	scheme = Scheme.for_cell('wlan0', 'home', cellName, passKey)
	scheme.save()
	scheme.activate()
else :
	scheme.delete()

######################################################################


"""

###################### Monitoring Connection ######################

class MonitoringConnection(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
Пример #49
0
             wifi = 1
             wait = 0.1
             estado = 2
     except:
         log(5, "Imposible leer redes wifi error de wlan0"  )
         wifi = 0
         conectado=0
         internet=0
         estado = 0
         wait= 10
         
 elif estado ==2:
     if (Scheme.find("wlan0", wifissid) == None ):
         # se guarda:
         try:
             scheme = Scheme.for_cell("wlan0",wifissid, cell[0], wificode )
             scheme.save()
             log(0, "red -%s- guardada."%wifissid)
             wifi = 1
             estado = 3
             wait= 0.1
             errores = 0
         except:
             try:
                 scheme.delete()
             except:
                 pass
             log(3, "Imposible guardar la wifissid  %s " %wifissid )
             wifi = 0
             conectado=0
             internet=0
Пример #50
0
 def create_scheme(self, ssid, password):
     cell = Cell.all(self.iface)
     scheme = Scheme.for_cell(self.iface, ssid, cell, password)
     scheme.save()
     scheme.activate()
Пример #51
0
# connect to network
from wifi import Cell, Scheme

# wifi information
wifi_ssid = "labpump123"
wifi_password = "******"

# machine information
port = Cell.all('wlan0')[0]

print "Connecting..."

try:
    scheme = Scheme.for_cell('wlan0', wifi_ssid, port, wifi_password)
    scheme.save()

except:
    scheme = Scheme.find('wlan0', wifi_ssid)

finally:
    scheme.activate();

# check internet connection
from pythonwifi.iwlibs import Wireless

network = Wireless('wlan0')
print "Connected with "+network.getEssid()+"."
print ("" if network.getMode()=="Managed" else "Not ")+"Secured Connection."