Beispiel #1
0
def get_wifi_devs():
    try:
        from wireless import Wireless
        w = Wireless()
        return w.interfaces()
    except:
        return []
Beispiel #2
0
def getMyMac():
	try:
		wireless = Wireless()
		ifaces = wireless.interfaces()
		iface = ifaces[-1]
		mac = (netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'])
		return mac
	except:
		print("Please manually select your interface using ifconfig or ipconfig using the -i flag")
		sys.exit(-1)
Beispiel #3
0
    def get_networks(self):
        wireless = Wireless()
        ifs = wireless.interfaces()
        if len(ifs) == 0:
            return []

        res = []
        for c in Cell.all(ifs[0]):
            res.append(c.ssid)

        return res
Beispiel #4
0
def configure():
    wireless = Wireless()
    wireless_interfaces = wireless.interfaces()
    if not len(wireless_interfaces):
        print('Wireless interface could not be found on your device.')
        return None
    elif len(wireless_interfaces) > 1:
        while True:
            print("Choose interface: ")
            for i in range(0, len(wireless_interfaces)):
                print("{}: {}".format(str(i), wireless_interfaces[i]))
            try:
                wireless_interface_number = int((input("Enter number: ")))
            except:
                continue
            if wireless_interface_number >= len(wireless_interfaces):
                continue
            wlan = wireless_interfaces[wireless_interface_number]
            break
    else:
        wlan = wireless_interfaces[0]
        print('Wlan interface found: {}'.format(wlan))

    remaining_interfaces = netifaces.interfaces()
    remaining_interfaces.remove(wlan)
    if not len(remaining_interfaces):
        inet = None
        print(
            'No network nic could be found on your deivce to interface with the LAN'
        )
    else:
        while True:
            print("Choose interface: ")
            for i in range(0, len(remaining_interfaces)):
                print("{}: {}".format(str(i), remaining_interfaces[i]))
            print("X: Do not use forwarding")
            try:
                remaining_interface_number = input("Enter number: ")
                if remaining_interface_number.lower() == "x":
                    inet = None
                    break
                remaining_interface_number = int(remaining_interface_number)
            except:
                continue
            if remaining_interface_number >= len(remaining_interfaces):
                continue
            inet = remaining_interfaces[remaining_interface_number]
            break

    while True:
        ip = input('Enter an IP address for your ap [192.168.45.1]:')
        ip = '192.168.45.1' if ip == '' else ip

        if not validate_ip(ip):
            continue

        break

    netmask = '255.255.255.0'

    ssid = input('Enter SSID [MyHotspot]:')
    ssid = 'MyHotspot' if ssid == '' else ssid

    password = input('Enter password [1234567890]:')
    password = '******' if password == '' else password

    encryption = input('Enter encryption [free]:')
    encryption = 'free' if encryption == '' else encryption

    return create_config_json(wlan, inet, ip, netmask, ssid, encryption,
                              password)
Beispiel #5
0
class ServerBrain:
    def __init__(self, socket=None):

        self.socket = socket
        #used to switch connection
        self.connectionManager = Wireless()

        #array of drone initializer
        self.drones = {'Solo Gold': None, 'Solo Green': None}

    '''
	This method returns a list that contains the name of the drones in the system
	'''

    def getDroneNames(self):
        droneList = list()
        for drone in self.drones:
            droneList.append(drone)
        return droneList

    '''
	This method is used for creating an instance of the class Drone.
	'''

    def connectDrone(self, droneName):
        '''
		Trying to find a free network for the drone
		'''

        interface, network = self.__getNetwork__(droneName, 'drone')
        if (interface, network) == (False, False):
            return droneName + " network is not reacheable"
        else:
            infosToReturn = {}
            self.drones[droneName] = Drone(droneName, interface, network)
            try:
                self.drones[droneName].connect()
                infosToReturn['drone status'] = 'available'
                infosToReturn['home location'] = self.drones[
                    droneName].getCurrentLocation()
                infosToReturn['drone battery'] = self.drones[
                    droneName].getBattery()
                infosToReturn['camera status'] = 'available'
                return infosToReturn
            except Exception as e:
                print "Error on establishing a connection with the " + droneName
                #raise
                return "timeout expired"

    '''
	This method assigns the locations to reach to the Solo passed as parameter.
	'''

    def buildPath(self, droneName, locationsToReach):
        '''
		algorithm for building a path for droneName
		'''
        self.drones[droneName].buildListOfLocations(locationsToReach)
        return {
            'drone':
            droneName,
            'locations to reach':
            self.drones[droneName].serializeListOfLocationsToReach()
        }

    def buildRandomPath(self, droneInvolved):
        if self.drones[droneInvolved] is None:
            return "ERROR"
        import randomflytry
        randomSurveyLocation = randomflytry.randMissionRead('randMission.txt')
        locations = []
        for location in randomSurveyLocation['picList']:
            '''
			location is a mission class instance. I can access to the single location values in a simple way:
			- location.latitude
			- location.longitude
			- location.altitude
			'''
            locations.append({
                "latitude": location.latitude,
                "longitude": location.longitude,
                "altitude": location.altitude
            })
            pass
        self.drones[droneInvolved].buildListOfLocations(locations)
        return {'drone': droneInvolved, 'locations': locations}

    '''
	This method generates the points inside the rectangular area delimited by the 3 points sent by client.
	If the 3 points are perfectly put from client, this method will return all the points to client and moreover it will assing these points to
	each Solo involved in the survey. Otherwise it will notify the client of the possibile errors it has got.
	'''

    def buildRectangularSurveyPointsReal(self, data):

        points = data['locationsList']
        altitude = points[0]['altitude']
        involvedDrones = data['drones']
        #check if involved drones are connected
        for drone in involvedDrones:
            if self.drones[drone] == None:
                missionDivisionData = {
                    'response':
                    'Connection Error',
                    'body':
                    'You need to be connected with the drones involved in the rectangular survey'
                }
                return missionDivisionData
        pointsNewFormat = []
        import rectPlan
        for point in points:
            pointsNewFormat.append(
                rectPlan.latlon(point['latitude'], point['longitude']))

        result = rectPlan.rectMission(pointsNewFormat[0], pointsNewFormat[1],
                                      pointsNewFormat[2], altitude)
        if result == 'Bad':
            return result
        #print "Result: ", result['picList']

        droneList = []
        for drone in data['drones']:
            droneList.append(drone)
            location = self.drones[drone].getCurrentLocation()
            droneList.append(location['latitude'])
            droneList.append(location['longitude'])

        missionDivisionData = rectPlan.missionDivision(result, droneList)
        missionDivisionData = rectPlan.serializeMissionData(
            missionDivisionData)
        '''
		Assign locations to reach to each involved drone
		'''
        if missionDivisionData['response'] == 'Good' or missionDivisionData[
                'response'] == 'Warn':
            #filling the locationsToReach array for each involved drone
            for UAVInfo in missionDivisionData['UAVs']:
                drone = UAVInfo['name']
                self.drones[drone].buildListOfLocations(UAVInfo['points'])
        return missionDivisionData

    '''
	Same of precedent method but cheating...
	'''

    def buildRectangularSurveyPointsCheating(self, data):
        points = data['locationsList']
        altitude = points[0]['altitude']
        involvedDrones = data['drones']
        #check if involved drones are connected
        for drone in involvedDrones:
            if self.drones[drone] == None:
                missionDivisionData = {
                    'response':
                    'Connection Error',
                    'body':
                    'You need to be connected with the drones involved in the rectangular survey'
                }
                return missionDivisionData
        pointsNewFormat = []
        import rectPlan
        for point in points:
            pointsNewFormat.append(
                rectPlan.latlon(point['latitude'], point['longitude']))

        result = rectPlan.rectMission(pointsNewFormat[0], pointsNewFormat[1],
                                      pointsNewFormat[2], altitude)
        if result == 'Bad':
            return result
        #print "Result: ", result['picList']

        droneList = []
        for drone in data['drones']:
            droneList.append(drone)
            location = self.drones[drone].getCurrentLocation()
            droneList.append(location['latitude'])
            droneList.append(location['longitude'])

        missionDivisionData = rectPlan.missionDivisionCheating(
            result, droneList, data['total'])
        #missionDivisionData = rectPlan.missionDivision(result, droneList)
        missionDivisionData = rectPlan.serializeMissionData(
            missionDivisionData)
        #dataToReturn is required for keeping data on missionDivisionData correct. In fact with the modify of "completed" field in eache UAVInfo object,
        #the risk is that client could not understand which points to show. File will be modified with the missionDivisionData updated for each drone("completed" key's value).
        dataToReturn = missionDivisionData
        '''
		Assign locations to reach to each involved drone
		'''
        if missionDivisionData['response'] == 'Good' or missionDivisionData[
                'response'] == 'Warn':
            #filling the locations to reach array for each drone involved
            UAVInfo = missionDivisionData['UAVs']
            for index in xrange(0, len(UAVInfo)):
                drone = UAVInfo[index]['name']
                #if drone has already a filled list of locations to reach, I need to go ahead
                #otherwise I need to understand if the mission has been already completed and if not I can assign points to the associated drone and set the key "completed" to True
                if self.drones[drone] is not None:
                    if self.drones[drone].listOfLocationsToReach is None:
                        self.drones[drone].buildListOfLocations(
                            UAVInfo[index]['points'])
                        UAVInfo[index]['to complete'] = True
                else:
                    print "This drone has already locations to reach"
            missionDivisionData['UAVs'] = UAVInfo
            file = open("oldSurvey.txt", "w")
            file.write(str(missionDivisionData))
            file.close()
        return dataToReturn

    '''
	This method allows to upload the points to reach by the Solos from a file where there is a dictionary with a particular structure.
	The structure of the dictionary is:
		missionDivisionData = {
			'response' : 'Good|Warm|Error',
			'UAVs' : [ {
				'name' : '..',
				'points' : [loc1, loc2, ...],
				'to complete' : True|False,
				'completed' : True|False
			},
			{
				'name' : '..',
				'points' : [loc1, loc2, ...],
				'to complete' : True|False,
				'completed' : True|False
			}]
		}
	As you can see the dictionary contains information about the last multiple flight that has involved multiple Solos.
	This method searches for that element of the array in missionDivisionData['UAVs'] that belongs to a connected Solo and that has key 'to complete' set to True.
	Once it finds the element of the array, it will upload the points in the key 'points' to the current listOfLocationsToReach associated to the current Solo.
	After the uploading (that can involve multiple Solos), this method will update the file with the new information about the old survey.
	'''

    def checkOldSurvey(self):
        #taking information about old survey not completed
        missionDivisionData = (open("oldSurvey.txt", "r").read())
        if len(missionDivisionData) == 0:
            return "No old survey to end"
        missionDivisionData = eval(missionDivisionData)
        #dataToReturt is required for keeping data on missionDivisionData correct. In fact with the modify of "completed" field in eache UAVInfo object,
        #the risk is that client could not understand which points to show. File will be modified with the missionDivisionData updated for each drone("completed" key's value).
        dataToReturn = missionDivisionData
        UAVInfo = missionDivisionData['UAVs']
        for index in xrange(0, len(UAVInfo)):
            drone = UAVInfo[index]['name']
            #if drone has already a filled list of locations to reach, I need to go ahead
            #otherwise I need to understand if the mission has been already completed and if not I can assign points to the associated drone and set the key "completed" to True
            if self.drones[drone] is not None:
                if self.drones[drone].listOfLocationsToReach is not None:
                    print drone + " has already locations to reach"
                else:
                    print drone + " has an empty list of locations"
                    if UAVInfo[index]['completed'] == False:
                        self.drones[drone].buildListOfLocations(
                            UAVInfo[index]['points'])
                        UAVInfo[index]['to complete'] = True
                    else:
                        print "This set of points has been completed"
        missionDivisionData['UAVs'] = UAVInfo
        file = open("oldSurvey.txt", "w")
        file.write(str(missionDivisionData))
        file.close()
        return dataToReturn

    '''
	This method creates a thread for a drone's flight.
	'''

    def takeAFlight(self, drone):
        if self.drones[
                drone] is not None and self.drones[drone].firstFlight is False:
            print drone + " has already had a flight, for the next flight I need to clear its memory.."
            self.drones[drone].cleanTheMemory()

        # we use the singleFlightWithTheUsingOfSolosMemory for the random flight
        eventlet.spawn(
            self.drones[drone].singleFlightWithTheUsingOfSolosMemory,
            self.connectionManager, self.socket)

    '''
	This method allows the drone to have an oscillation flight.
	'''

    def takeAnOscillationFlight(self, drone):
        data = self.drones[drone].oscillationFlight()
        return data

    '''
	This method starts the rectangular survey flight creating threads for each Solo involved.
	'''

    def takeARectangularFlight(self):
        #I need to be sure that the memory has been cleaned
        for drone in self.drones:
            if self.drones[drone] is not None and self.drones[
                    drone].firstFlight is False:
                print drone + " has already had a flight, for the next flight I need to clear its memory.."
                self.drones[drone].cleanTheMemory()

        for drone in self.drones:
            if self.drones[drone] is not None:
                if len(self.drones[drone].listOfLocationsToReach) > 0:
                    print "launching the thread for " + drone + " for having a flight."
                    eventlet.spawn(
                        self.drones[drone].flightWithTheUsingOfSolosMemory,
                        self.connectionManager, self.socket)
                    eventlet.sleep(15)
                    #time.sleep(10)

    '''
	This method is used for building the wifi network name the drone will connect to.
	'''

    def __getNetworkName__(self, type, drone):
        color = drone.split(
        )[1]  # I've just taken the drone color from drone name(ex:'Solo Gold')
        if type == "drone":
            print "Drone setting network"
            wifiNetwork = "SoloLink_" + color + "Drone"
        return wifiNetwork

    '''
	This method is designed in order to get network interface value and wifi network name for the Solo.
	'''

    def __getNetwork__(self, drone, type):
        wifiNetwork = self.__getNetworkName__(type, drone)
        print wifiNetwork
        '''This for-loop checks if this network is already connected '''
        for interface in self.connectionManager.interfaces():
            self.connectionManager.interface(interface)
            print self.connectionManager.current()
            if self.connectionManager.current() == wifiNetwork:
                print "You are already connected to this network, ", wifiNetwork
                self.connectionManager.connect(ssid=wifiNetwork,
                                               password="******")
                return self.connectionManager.interface(
                ), self.connectionManager.current()
            print self.connectionManager.current()
        '''This for-loop checks if this network has not a connection yet '''
        for interface in self.connectionManager.interfaces():
            self.connectionManager.interface(interface)
            if self.connectionManager.current() == None:
                print "I've just found one free antenna ready to be connected"
                if self.connectionManager.connect(ssid=wifiNetwork,
                                                  password="******"):
                    return self.connectionManager.interface(
                    ), self.connectionManager.current()
                else:
                    '''This could be possible if the network is not available '''
                    print "Network not available"
                    return False, False

        print "I haven't found a free antenna for your connection... sorry, ", wifiNetwork
        return False, False

    def closeBrain(self):
        for drone in self.drones:
            if self.drones[drone] is not None:
                print "closing connection with the vehicle of " + drone
                self.drones[drone].vehicle.close()
            self.drones[drone] = None
Beispiel #6
0
# function to check the presense of SSID
def is_present (candidate):
    subprocess.call(["airport -s -x>ssids.xml"], shell=True)
    myplist = plistlib.readPlist('ssids.xml')
    print 'The current list is:', myplist
    for el in myplist:
        if candidate == el.get('SSID_STR'):
            print 'State is valid'
            return True
    print 'State is not valid'
    return False

wireless = Wireless()
print "Current: ", wireless.current()
print "Interfaces: ",wireless.interfaces()

# ---------  Open the files
lines = [line.strip() for line in open("Untitled.txt", 'r')]
dones = [line.strip() for line in open("Done.txt", 'r')]
subprocess.call(["airport -s -x>ssids.xml"], shell=True)
f= open('Results.txt', 'a')
f2= open('Done.txt', 'a')
result = plistlib.readPlist('ssids.xml')
print 'Already done: ', dones

i = 0
# ------  Going to scan
for elem in result:
    victim = elem.get('SSID_STR')
    if (victim not in dones) and (is_present(victim)):
Beispiel #7
0
config = ConfigParser.RawConfigParser()
config.read("/usr/local/mindsensors/conf/msdev.cfg")
homefolder = config.get("msdev", "homefolder")
currentdir = os.path.join(homefolder, "programs")

# Globals
config_file = "/etc/wpa_supplicant/wpa_supplicant.conf" # Config file for Wi-Fi
wifi = None
wlan_inteface = "wlan0"
psm = PiStorms_GRX()

# Check if a wifi adapter is available
try:
    wifi = Wireless()
    wlan_interface = wifi.interfaces()[0]
except Exception as e:
    psm.screen.fillRect(0, 0, 320, 240, fill = (0,0,0), display = False)
    psm.screen.drawAutoText("No Wi-Fi adapter", 35, 20, fill = (255,0,0), size = 25, display = False)
    psm.screen.drawAutoText("available!", 35, 50, fill = (255,0,0), size = 25, display = False)
    psm.screen.drawButton(35, 160, width = 250, height = 40, text="Continue", display=False)
    psm.screen.fillRect(0, 0, 1, 1, fill = (0,0,0), display = True)
    while True:
        cont = psm.screen.checkButton(35, 160, 250, 40)
        if cont: sys.exit(0)

current = wifi.current() # Currently connected network
available = Cell.all(wlan_interface) # Available networks
box = TouchScreenInput(psm.screen)

# Writes wifi configuration to wpa_supplicant.conf
Beispiel #8
0
def main(args):
    parser = argparse.ArgumentParser(
        description='Find active users on the current wireless network.')
    parser.add_argument('-p',
                        '--packets',
                        default=1000,
                        type=int,
                        help='How many packets to capture.')
    parser.add_argument('-i',
                        '--interface',
                        default=None,
                        type=str,
                        help='Which wireless interface to use.')
    parser.add_argument('-s',
                        '--ssid',
                        default=None,
                        type=str,
                        help='Which SSID to use.')
    parser.add_argument('-r',
                        '--results',
                        default=None,
                        type=int,
                        help='How many results to show.')
    args = parser.parse_args()

    try:
        if args.interface:
            iface = args.interface
        else:
            wireless = Wireless()
            ifaces = wireless.interfaces()
            eprint('Available interfaces: {}'.format(', '.join(ifaces)))
            iface = ifaces[-1]
        eprint('Interface: {}'.format(iface))

        if args.ssid:
            ssid = args.ssid
        else:
            wireless = Wireless()
            ssid = wireless.current()
            if ssid is None:
                eprint(NO_SSID)
                return
        eprint('SSID: {}'.format(ssid))
    except:
        eprint(NO_WIRELESS)
        raise

    mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}'
    mac_re = re.compile(mac_re_str, re.I)
    network_macs = set()
    try:
        gws = netifaces.gateways()[netifaces.AF_INET]
        gw_ifaces = ', '.join([gw[1] for gw in gws])
        eprint('Available gateways: {}'.format(gw_ifaces))
        gw_ip = next(gw[0] for gw in gws if gw[1] == iface)
        eprint('Gateway IP: {}'.format(gw_ip))
        gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)])
        gw_arp = gw_arp.decode('utf-8')
        gw_mac = EUI(mac_re.search(gw_arp).group(0))
        gw_mac.dialect = mac_unix_expanded
        network_macs.add(gw_mac)
        eprint('Gateway MAC: {}'.format(gw_mac))
    except StopIteration:
        eprint('No gateway for {}'.format(iface))
    except KeyError:
        eprint('No gateways available: {}'.format(netifaces.gateways()))
    except:
        eprint(NO_GATEWAY_MAC)

    bssid_re = re.compile(' BSSID:(\S+) ')

    tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I)
    length_re = re.compile(' length (\d+)')
    client_macs = set()
    data_totals = defaultdict(int)

    cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split()
    try:
        bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}'
        progress = tqdm(run_process(cmd),
                        total=args.packets,
                        bar_format=bar_format)
        for line in progress:
            line = line.decode('utf-8')

            # find BSSID for SSID
            if ssid in line:
                bssid_matches = bssid_re.search(line)
                if bssid_matches:
                    bssid = bssid_matches.group(1)
                    if 'Broadcast' not in bssid:
                        network_macs.add(EUI(bssid))

            # count data packets
            length_match = length_re.search(line)
            if length_match:
                length = int(length_match.group(1))
                mac_matches = tcpdump_mac_re.findall(line)
                if mac_matches:
                    macs = set([EUI(match[1]) for match in mac_matches])
                    leftover = macs - network_macs
                    if len(leftover) < len(macs):
                        for mac in leftover:
                            data_totals[mac] += length
                            client_macs.add(mac)

        if progress.n < progress.total:
            eprint('Sniffing finished early.')

    except subprocess.CalledProcessError:
        eprint('Error collecting packets.')
        raise
    except KeyboardInterrupt:
        pass

    totals_sorted = sorted(data_totals.items(),
                           key=lambda x: x[1],
                           reverse=True)

    eprint('Total of {} user(s)'.format(len(totals_sorted)))

    for mac, total in reversed(totals_sorted[:args.results]):
        mac.dialect = mac_unix_expanded
        if total > 0:
            print('{}\t{} bytes'.format(mac, total))
Beispiel #9
0
# function to check the presense of SSID
def is_present(candidate):
    subprocess.call(["airport -s -x>ssids.xml"], shell=True)
    myplist = plistlib.readPlist('ssids.xml')
    print 'The current list is:', myplist
    for el in myplist:
        if candidate == el.get('SSID_STR'):
            print 'State is valid'
            return True
    print 'State is not valid'
    return False


wireless = Wireless()
print "Current: ", wireless.current()
print "Interfaces: ", wireless.interfaces()

# ---------  Open the files
lines = [line.strip() for line in open("Untitled.txt", 'r')]
dones = [line.strip() for line in open("Done.txt", 'r')]
subprocess.call(["airport -s -x>ssids.xml"], shell=True)
f = open('Results.txt', 'a')
f2 = open('Done.txt', 'a')
result = plistlib.readPlist('ssids.xml')
print 'Already done: ', dones

i = 0
# ------  Going to scan
for elem in result:
    victim = elem.get('SSID_STR')
    if (victim not in dones) and (is_present(victim)):
Beispiel #10
0
def main(args):
    parser = argparse.ArgumentParser(
        description='Find active users on the current wireless network.')
    parser.add_argument('-p', '--packets',
                        default=1000,
                        type=int,
                        help='How many packets to capture.')
    parser.add_argument('-i', '--interface',
                        default=None,
                        type=str,
                        help='Which wireless interface to use.')
    parser.add_argument('-s', '--ssid',
                        default=None,
                        type=str,
                        help='Which SSID to use.')
    parser.add_argument('-r', '--results',
                        default=None,
                        type=int,
                        help='How many results to show.')
    args = parser.parse_args()

    try:
        if args.interface:
            iface = args.interface
        else:
            wireless = Wireless()
            ifaces = wireless.interfaces()
            eprint('Available interfaces: {}'.format(', '.join(ifaces)))
            iface = ifaces[-1]
        eprint('Interface: {}'.format(iface))

        if args.ssid:
            ssid = args.ssid
        else:
            wireless = Wireless()
            ssid = wireless.current()
            if ssid is None:
                eprint(NO_SSID)
                return
        eprint('SSID: {}'.format(ssid))
    except:
        eprint(NO_WIRELESS)
        raise

    mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}'
    mac_re = re.compile(mac_re_str, re.I)
    network_macs = set()
    try:
        gws = netifaces.gateways()[netifaces.AF_INET]
        gw_ifaces = ', '.join([gw[1] for gw in gws])
        eprint('Available gateways: {}'.format(gw_ifaces))
        gw_ip = next(gw[0] for gw in gws if gw[1] == iface)
        eprint('Gateway IP: {}'.format(gw_ip))
        gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)])
        gw_arp = gw_arp.decode('utf-8')
        gw_mac = EUI(mac_re.search(gw_arp).group(0))
        gw_mac.dialect = mac_unix_expanded
        network_macs.add(gw_mac)
        eprint('Gateway MAC: {}'.format(gw_mac))
    except StopIteration:
        eprint('No gateway for {}'.format(iface))
    except KeyError:
        eprint('No gateways available: {}'.format(netifaces.gateways()))
    except:
        eprint(NO_GATEWAY_MAC)

    bssid_re = re.compile(' BSSID:(\S+) ')

    tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I)
    length_re = re.compile(' length (\d+)')
    client_macs = set()
    data_totals = defaultdict(int)

    cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split()
    try:
        bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}'
        progress = tqdm(run_process(cmd),
                        total=args.packets,
                        bar_format=bar_format)
        for line in progress:
            line = line.decode('utf-8')

            # find BSSID for SSID
            if ssid in line:
                bssid_matches = bssid_re.search(line)
                if bssid_matches:
                    bssid = bssid_matches.group(1)
                    if 'Broadcast' not in bssid:
                        network_macs.add(EUI(bssid))

            # count data packets
            length_match = length_re.search(line)
            if length_match:
                length = int(length_match.group(1))
                mac_matches = tcpdump_mac_re.findall(line)
                if mac_matches:
                    macs = set([EUI(match[1]) for match in mac_matches])
                    leftover = macs - network_macs
                    if len(leftover) < len(macs):
                        for mac in leftover:
                            data_totals[mac] += length
                            client_macs.add(mac)

        if progress.n < progress.total:
            eprint('Sniffing finished early.')

    except subprocess.CalledProcessError:
        eprint('Error collecting packets.')
        raise
    except KeyboardInterrupt:
        pass

    totals_sorted = sorted(data_totals.items(),
                           key=lambda x: x[1],
                           reverse=True)

    eprint('Total of {} user(s)'.format(len(totals_sorted)))

    for mac, total in reversed(totals_sorted[:args.results]):
        mac.dialect = mac_unix_expanded
        if total > 0:
            print('{}\t{} bytes'.format(mac, total))
Beispiel #11
0
'''
wifi.py

Various wifi scripts that are useful
https://pypi.org/project/wireless/
https://github.com/joshvillbrandt/wireless
'''

from wireless import Wireless

# connect to wireless network
wireless = Wireless()
ssid = 'I_am_cool'
password = '******'
wireless.connect(ssid='ssid', password='******')

# various things you can get
print(wireless.current())
print(wireless.interfaces())
print(wireless.interface())
print(wireless.power())
print(wireless.driver())
Beispiel #12
0
def main():

	parser = argparse.ArgumentParser(
		description='Find active users on the current wireless network.')
	parser.add_argument('-p', '--packets',
						default=100,
						type=int,
						help='How many packets to capture.')
	parser.add_argument('-i', '--interface',
						default='en0',
						type=str,
						help='Which wireless interface to use.')
	parser.add_argument('-v', '--verbose',
						action='store_true')
	parser.add_argument('-f', '--file',
						action='store_true',
						help='logs the trace.txt and nmap.txt')
	parser.add_argument('-changeMAC', '--mac',
						default=None,
						type=str,
						help='MAC addres to change to.')

	args = parser.parse_args()

	if (args.mac == None):
		myIP = (socket.gethostbyname(socket.gethostname()))
		mac = getMyMac()
		allSources = {}
		verbose = args.verbose
		print ("-------------------Previous data -----------------")
		print ("Previous MAC address: " + mac + "        My IP:  " + myIP)
		print ("-------------------TCP data collection------------")
		tcpSources = collectDataTCP(args.packets, args.interface, allSources)
		if (verbose):
			printSources(tcpSources)
		print ("Done")
		print ("-------------------NMAP data collection------------")
		nmapSources = collectDataNMAP(allSources)
		if (verbose):
			printSources(nmapSources)
		print ("Done")
		print ("-------------------Tshark data collection----------")
		sharkSources = collectDataWShark(args.packets, args.interface, allSources)
		if (verbose):
			printSources(sharkSources)
		print ("Done")
		print ("-------------------All Data results----------------")
		allSources = cleanData(allSources)
		high = changeMac(allSources, True)
		print ("---------------------------------------------------")
	else :
		m = ""
		m = re.search(r'[a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}[:][a-fA-F0-9]{2}', args.mac)
		if (m == ""):
			print ("Error on MAC input")
		else:
			platform = sys.platform
			wireless = Wireless()
			ifaces = wireless.interfaces()
			iface = ifaces[-1]
			if (platform == 'linux' or platform == 'linux2'):
				os.system("/etc/init.d/networking stop") 
				os.system("ifconfig " + iface + " hw ether " + args.mac) 
				os.system("/etc/init.d/networking start") 
			elif (platform == 'darwin'):
				os.system("sudo ifconfig en0 ether " + args.mac)
			elif (platform == 'win32'):
				print ("Not implemented")
			else:
				print ("Unknown Operating system")
			print ("Changing MAC to: " + args.mac)
			print ("Remember, it may take over 30 seconds to reconnect after your MAC address is changed.")
			if os.path.exists('trace.txt') and args.file:
				os.remove('trace.txt')
			if os.path.exists('nmap.txt') and args.file:
				os.remove('nmap.txt')