Example #1
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
Example #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
Example #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
Example #4
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
Example #5
0
def autoconnect_command(interface):
    ssids = [cell.ssid for cell in Cell.all(interface)]
    connected = False
    for scheme in [
            Scheme.find('wlan0', s)
            for s in ['scheme-' + str(x) for x in range(1, 6)]
    ]:
        ssid = scheme.options.get('wpa-ssid',
                                  scheme.options.get('wireless-essid'))
        if ssid in ssids:
            sys.stderr.write('Connecting to "%s".\n' % ssid)
            try:
                scheme.activate()
                connected = True
            except ConnectionError:
                print "Failed to connect to %s." % scheme.name
                continue
            connected = True
            break

    if not connected:
        try:
            s = Scheme.find('wlan0', 'hotspot')
            s.activate()
        except ConnectionError:
            print "hotspot is created."
Example #6
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()
Example #7
0
File: weech.py Project: nbdy/weech
 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
Example #8
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)
Example #9
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
Example #10
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
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()
Example #13
0
File: weech.py Project: nbdy/weech
 def parse():
     c = Configuration()
     i = 0
     while i < len(argv):
         a = argv[i]
         if a in ["--help"]:
             Configuration.help()
         elif a in ["-h", "--host"]:
             c.host = argv[i + 1]
         elif a in ["-p", "--port"]:
             c.port = int(argv[i + 1])
         elif a in ["-d", "--debug"]:
             c.debug = True
         elif a in ["--add-scheme"]:
             for iface in argv[i + 1].split(","):
                 if iface in interfaces():
                     print(iface, argv[i + 3], argv[i + 2])
                     Utils.connect(iface, argv[i + 3], argv[i + 2])
                 else:
                     print(iface, "not in", interfaces())
             exit()
         elif a in ["--get-scheme"]:
             print(Scheme.find(argv[i + 1], argv[i + 2]))
             exit()
         i += 1
     return c
Example #14
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")
Example #15
0
def testmethod_1():
    print "Method testmethod_1 in class testclass_5"
    print "Method Assign IP address by static in class testclass_5"
    scheme = Scheme.find('wlan0','1234')
    time.sleep(5)
    scheme.activate()
    static_test = UITest()
    static_test.static_config_retest('192.168.100.243','255.255.255.0','0.0.0.0','0.0.0.0')
    browser = webdriver.Firefox()
    browser.get('http://172.16.9.9')
    time.sleep(3)
    ipConfigHeadIcon_value = browser.find_element_by_id("ipConfigHeadIcon").get_attribute('src')
    known_ipConfigHeadIcon_value = 'http://172.16.9.9/images/dhcpgreen.png'
    assert known_ipConfigHeadIcon_value == ipConfigHeadIcon_value
    ipConfigTitle_value = browser.find_element_by_id("ipConfigTitle").text
    assert ipConfigTitle_value == '192.168.100.243'
    print("ipConfigTitle = %s" % ipConfigTitle_value)
    browser.find_element_by_id("ipConfigHeadIcon").click()
    time.sleep(1)
    #dhcp_name = browser.find_element_by_id("dhcpName").text
    time.sleep(1)
    #dhcp_subnet = browser.find_element_by_id("dhcpSubnet").text
    time.sleep(1)
    dhcp_dns1 = browser.find_element_by_id("dhcpDns1").text
    time.sleep(1)
    print(dhcpname)
    print(dhcp_subnet)
    print(dhcp_dns1)
    #assert dhcp_name == u'Server:'
    #assert dhcp_subnet == u'Subnet:255.255.255.0'
    #assert dhcp_dns1 == u'DNS:'
    browser.quit()
Example #16
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()
Example #17
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)
Example #18
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")
Example #19
0
 def delete(self, name):
     s = [s for s in Scheme.all() if s.name == name]
     if len(s) > 0:
         s[0].delete()
         return jsonify({'response': "ok"})
     else:
         return jsonify({'response': "non found"})
Example #20
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
Example #21
0
def arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i',
                        '--interface',
                        default='wlan0',
                        help="Specifies which interface to use (wlan0, eth0, etc.)")
    parser.add_argument('-f',
                        '--file',
                        default='/etc/network/interfaces',
                        help="Specifies which file for scheme storage.")
    
    subparsers = parser.add_subparsers(title='commands')
    
    parser_scan = subparsers.add_parser('scan', help="Shows a list of available networks.")
    parser_scan.set_defaults(func=scan_command)
    
    parser_list = subparsers.add_parser('list', help="Shows a list of networks already configured.")
    parser_list.set_defaults(func=list_command)
    
    scheme_help = ("A memorable nickname for a wireless network."
                   "  If SSID is not provided, the network will be guessed using SCHEME.")
    ssid_help = ("The SSID for the network to which you wish to connect."
                 "  This is fuzzy matched, so you don't have to be precise.")
    
    parser_show = subparsers.add_parser('config',
                                        help="Prints the configuration to connect to a new network.")
    parser_show.add_argument('scheme', help=scheme_help, metavar='SCHEME')
    parser_show.add_argument('ssid', nargs='?', help=ssid_help, metavar='SSID')
    parser_show.set_defaults(func=show_command)
    
    parser_add = subparsers.add_parser('add',
                                       help="Adds the configuration to connect to a new network.")
    parser_add.add_argument('scheme', help=scheme_help, metavar='SCHEME')
    parser_add.add_argument('ssid', nargs='?', help=ssid_help, metavar='SSID')
    parser_add.set_defaults(func=add_command)
    
    parser_connect = subparsers.add_parser('connect',
                                           help="Connects to the network corresponding to SCHEME")
    parser_connect.add_argument('scheme',
                                help="The nickname of the network to which you wish to connect.",
                                metavar='SCHEME')
    parser_connect.add_argument('-a',
                                '--ad-hoc',
                                dest='adhoc',
                                action="store_true",
                                help="Connect to a network without storing it in the config file")
    parser_connect.set_defaults(func=connect_command)
    
    
    # TODO: how to specify the correct interfaces file to work off of.
    parser_connect.get_options = lambda: [scheme.name for scheme in Scheme.all()]

    parser_autoconnect = subparsers.add_parser(
        'autoconnect',
        help="Searches for saved schemes that are currently"
             " available and connects to the first one it finds."
    )
    parser_autoconnect.set_defaults(func=autoconnect_command)

    return parser, subparsers
Example #22
0
File: cli.py Project: Evanito/wifi
def arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i',
                        '--interface',
                        default='wlan0',
                        help="Specifies which interface to use (wlan0, eth0, etc.)")
    parser.add_argument('-f',
                        '--file',
                        default='/etc/network/interfaces',
                        help="Specifies which file for scheme storage.")

    subparsers = parser.add_subparsers(title='commands')

    parser_scan = subparsers.add_parser('scan', help="Shows a list of available networks.")
    parser_scan.set_defaults(func=scan_command)

    parser_list = subparsers.add_parser('list', help="Shows a list of networks already configured.")
    parser_list.set_defaults(func=list_command)

    scheme_help = ("A memorable nickname for a wireless network."
                   "  If SSID is not provided, the network will be guessed using SCHEME.")
    ssid_help = ("The SSID for the network to which you wish to connect."
                 "  This is fuzzy matched, so you don't have to be precise.")

    parser_show = subparsers.add_parser('config',
                                        help="Prints the configuration to connect to a new network.")
    parser_show.add_argument('scheme', help=scheme_help, metavar='SCHEME')
    parser_show.add_argument('ssid', nargs='?', help=ssid_help, metavar='SSID')
    parser_show.set_defaults(func=show_command)

    parser_add = subparsers.add_parser('add',
                                       help="Adds the configuration to connect to a new network.")
    parser_add.add_argument('scheme', help=scheme_help, metavar='SCHEME')
    parser_add.add_argument('ssid', nargs='?', help=ssid_help, metavar='SSID')
    parser_add.set_defaults(func=add_command)

    parser_connect = subparsers.add_parser('connect',
                                           help="Connects to the network corresponding to SCHEME")
    parser_connect.add_argument('scheme',
                                help="The nickname of the network to which you wish to connect.",
                                metavar='SCHEME')
    parser_connect.add_argument('-a',
                                '--ad-hoc',
                                dest='adhoc',
                                action="store_true",
                                help="Connect to a network without storing it in the config file")
    parser_connect.set_defaults(func=connect_command)

    # TODO: how to specify the correct interfaces file to work off of.
    parser_connect.get_options = lambda: [scheme.name for scheme in Scheme.all()]

    parser_autoconnect = subparsers.add_parser(
        'autoconnect',
        help="Searches for saved schemes that are currently"
             " available and connects to the first one it finds."
    )
    parser_autoconnect.set_defaults(func=autoconnect_command)

    return parser, subparsers
Example #23
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();
Example #24
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
Example #25
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()
Example #26
0
File: cli.py Project: gamwe6/wifi
def add_command(args):
    scheme_class = Scheme.for_file(args.file)
    assert not scheme_class.find(
        args.interface, args.scheme), "That scheme has already been used"

    scheme = scheme_class.for_cell(
        *get_scheme_params(args.interface, args.scheme, args.ssid))
    scheme.save()
Example #27
0
def connect_to_wifi(name):
    try:
        scheme = Scheme.find('wlan0', name)
        scheme.activate()
        time.sleep(10)
    except:
        print("trying to recconect")
        scheme.activate()
        time.sleep(10)
Example #28
0
 def get(self, name):
     parser = reqparse.RequestParser()
     parser.add_argument('action')
     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]
     return jsonify({'scheme': scheme.__dict__})
Example #29
0
def auto_connect(ap, adapter):
    # Attempt connection on known available networks
    for cell in list_networks(ap):
        # List networks from AP interface (so our own network is excluded)
        scheme = Scheme.find(adapter, cell.ssid)
        if activate_scheme(scheme):
            # Connected
            return cell.ssid
    # Failed to connect
    return False
Example #30
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
Example #31
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
Example #32
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
Example #33
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."
Example #34
0
File: main.py Project: drwonky/NC
    def wifi_reconnect(self):
        wifiap = self.config.get('networking', 'wifiap')
        wifi_iface = self.config.get('networking', 'wifi_iface')

        try:
            scheme = Scheme.find(wifi_iface, wifiap)
            if scheme != None:
                activatethread = Thread(target=self.activate_thread,
                                        args=(scheme.activate, ))
                activatethread.start()
        except:
            pass
Example #35
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()
Example #36
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"])
Example #37
0
def tryToConnect():
    global connected
    file = open('.known_wifi', 'r')
    for line in file:
        scheme = Scheme.find(wifiInterface, line)
        if scheme:
            try:
                scheme.activate()
            except ConnectionError:
                continue
            connected = True
    connected = False
Example #38
0
def scheme_all():
    """
    return all schemes stored in /etc/network/interfaces

    :return: list of schemes as json string
    """
    schemes = Scheme.all()
    res = []

    for s in schemes:
        res.append(_scheme_to_dict(s))

    return res
Example #39
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"})
Example #40
0
File: cli.py Project: Evanito/wifi
def autoconnect_command(args):
    ssids = [cell.ssid for cell in Cell.all(args.interface)]

    for scheme in Scheme.all():
        # TODO: make it easier to get the SSID off of a scheme.
        ssid = scheme.options.get('wpa-ssid', scheme.options.get('wireless-essid'))
        if ssid in ssids:
            sys.stderr.write('Connecting to "%s".\n' % ssid)
            try:
                scheme.activate()
            except ConnectionError:
                assert False, "Failed to connect to %s." % scheme.name
            break
    else:
        assert False, "Couldn't find any schemes that are currently available."
Example #41
0
    def select_network(self):
        # Wifi select element
        self.selectwifi = builder.get_object("selectwifi")
        self.selectwifi.show()

        # List Interface
        self.list_interface = builder.get_object("list_interface")

        # List wifi networks
        ssids = [cell.ssid for cell in Cell.all("wlan0")]
        schemes = list(Scheme.all())

        # Fills the wifi select with available networks
        for ssid in ssids:
            self.treeiter = self.list_interface.append([ssid])
Example #42
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)
Example #43
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")
Example #44
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
Example #45
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
Example #46
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
Example #47
0
File: cli.py Project: Evanito/wifi
def connect_command(args):
    scheme_class = Scheme.for_file(args.file)
    if args.adhoc:
        # ensure that we have the adhoc utility scheme
        try:
            adhoc_scheme = scheme_class(args.interface, 'adhoc')
            adhoc_scheme.save()
        except AssertionError:
            pass
        except IOError:
            assert False, "Can't write on {0!r}, do you have required privileges?".format(args.file)

        scheme = scheme_class.for_cell(*get_scheme_params(args.interface, 'adhoc', args.scheme))
    else:
        scheme = scheme_class.find(args.interface, args.scheme)
        assert scheme, "Couldn't find a scheme named {0!r}, did you mean to use -a?".format(args.scheme)

    try:
        scheme.activate()
    except ConnectionError:
        assert False, "Failed to connect to %s." % scheme.name
Example #48
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 = ""
from wifi import Cell, Scheme
scheme = Scheme.find('wlan0', 'labpump123')
scheme.activate()
Example #50
0
#!/usr/bin/python
from __future__ import print_function

from wifi import Cell, Scheme

# get all cells from the air
ssids = [cell.ssid for cell in Cell.all('wlan0')]

schemes = list(Scheme.all())

for scheme in schemes:
    ssid = scheme.options.get('wpa-ssid', scheme.options.get('wireless-essid'))
    if ssid in ssids:
        print('Connecting to %s' % ssid)
        scheme.activate()
        break
Example #51
0
#wifi password
passKey = 'raspberry'
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):
Example #52
0
File: cli.py Project: Evanito/wifi
def list_command(args):
    for scheme in Scheme.for_file(args.file).all():
        print(scheme.name)
Example #53
0
File: cli.py Project: Evanito/wifi
def show_command(args):
    scheme = Scheme.for_file(args.file).for_cell(*get_scheme_params(args.interface, args.scheme, args.ssid))
    print(scheme)
Example #54
0
File: cli.py Project: Evanito/wifi
def add_command(args):
    scheme_class = Scheme.for_file(args.file)
    assert not scheme_class.find(args.interface, args.scheme), "That scheme has already been used"

    scheme = scheme_class.for_cell(*get_scheme_params(args.interface, args.scheme, args.ssid))
    scheme.save()
Example #55
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)
Example #56
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()