def runScan():
    # Initiliaze Parser and Commands
    parser = argparse.ArgumentParser(description = 'A WiFi Scanner parser used for file configurations')
    parser.add_argument("--fileName", type = str, required = True, help = "Used to name the output CSV file (Required)")
    parser.add_argument("--sigLimit", type = int, default = 50, help = "Minimum signal strength requested (i.e. 50, 72, 90). Default = 50")
    args = parser.parse_args()

    # Initialize Variables
    interface = 'wlp2s0'
    fileName = os.getcwd() + '/' + args.fileName + '.csv'
    stringList = []
    routerList = []
    refreshRate = 2 # Will wait this long (sec) before scanning again
    minRequiredRouters = 3 # How many routers do we need minimum?
    defaultListLength = 5
    routerListLen = len(routerList)
    
    # Start Scans until fulfilled minimum router requirements
    print("Scanning, please wait...")
    while(routerListLen < minRequiredRouters):
        routerList = working_interface.get_interfaces(interface)
        routerListLen = len(routerList)
        time.sleep(refreshRate)
    print("\nScan completed")

    # Organize Data into lists and strings
    stringList = displayReq(routerList, args.sigLimit)
    routerList = stringToList(stringList, defaultListLength)

    # Write to CSV file
    writeToFile(routerList, fileName)
Ejemplo n.º 2
0
def scan(interface="wlan0"):
    """
    Give the list of Access Points and Ad-Hoc cells in range.

    Optional arguments:
      - interface (str): Default is 'wlan0'.
    """

    return get_interfaces(interface=interface)
Ejemplo n.º 3
0
def scanWifiIwparse():
    try:
        logger.log("started scanning...")
        time = datetime.now()
        scan_output = iw_parse.get_interfaces('wlan0')
        logger.log("finished iw_parse")
        scan_results = {}

        def extract(cell, prop):
            try:
                return None if (prop not in cell
                                or cell[prop] == '') else cell[prop]
            except Exception as error:
                logger.log("Error in extract1")
                logger.log(error)
                logger.log("Error in extract2")
                return None

        for cell in scan_output:
            if 'Address' in cell:
                try:
                    ap_dict = {
                        'bssid': extract(cell, 'Address'),
                        'rssi': extract(cell, 'Signal Level'),
                        'ssid': extract(cell, 'Name'),
                        'time': str(time),
                        'channel': extract(cell, 'Channel'),
                        'quality': extract(cell, 'Quality'),
                        'bit_rate': extract(cell, 'Bit Rates'),
                        'last_beacon': extract(cell, 'Beacon'),
                        'encryption': extract(cell, 'Encryption')
                    }
                    if ap_dict['last_beacon']:
                        ap_dict['last_beacon'] = int(
                            ap_dict['last_beacon'].replace('ms ago', ''))
                    scan_results[cell['Address']] = ap_dict
                except Exception as error:
                    logger.log(error)
                    continue
            else:
                logger.log("Cell has no address")
                logger.log(cell)

        logger.log(scan_results)
        output = {}
        output['time'] = str(time)
        output['result'] = scan_results
        return output

    except Exception as error:
        logger.log(error)
        raise error
def getCSV():
    ### Constants ###
    interface = 'wlp2s0' # Network scanning device
    running_iter = 1 # Starting scan iteraction counter
    total_iter = 1 # Total scan interations
    refresh_rate = 1 # Delay between each scan in seconds
    minimum_router_list = 3 # The minimum amount of routers scanned
    interface_list = [] # Initial list of the interface list
    raw_string_list = [] # List of string lists
    default_list_length = 5 # Capture 4 items in the raw string list
    default_file_path = None
    default_csv_header_flag = True # Will add a header to the CSV file if true

    testvar = 0

    # To compare results to information obtained from the 
    # computer itself, run the following command in the 
    # ubuntu terminal:
    #     watch -n1 iwconfig
    # NOTE: This command shows the user what router and network is connected to
    while(running_iter <= total_iter ):
        # Collect connected router information
        # Show current iteration
        while(len(interface_list) < minimum_router_list and testvar < 3):
            print "Length of interface list: {}".format(len(interface_list))
            interface_list = working_interface.call_iwlist(interface).split()
            print "Length of interface list: {}".format(len(interface_list))
            testvar += 1
        # Pretty printing
        print "\n\n><><><><><><><><><><><><><><><"
        print "><><><>< Iteration {}  ><><><><".format(running_iter)
        print "><><><><><><><><><><><><><><><\n"
        new_list = working_interface.get_interfaces(interface)
        print(len(new_list))

        # Display All Routers
        rawDataString = displayReq(new_list)
        finalList = stringToList(rawDataString, default_list_length)

        # Write info to CSV file
        writeToFile(finalList, default_file_path, default_csv_header_flag)
        time.sleep(refresh_rate)
        running_iter += 1
        
        
    
    
    print "\n\nScanning terminated...\n\n" 
Ejemplo n.º 5
0
        led6.off()
    elif (level == 7):
        led7.off()
    elif (level == 8):
        led8.off()
    elif (level == 9):
        led9.off()
    elif (level == 10):
        led10.off()  


initialize()
lcd.clear()
lcd.display_lcd_line2("Scanning...")
while(True):
    wifilist = iw_parse.get_interfaces(interface="wlan1")
    if (is_network_in_list(wifilist, network_name)):
        network = get_network(wifilist, network_name)
        dbLevel = int(network["Signal Level"])
        level = get_level(dbLevel)
        lcd.display_lcd_line1("level = " + str(level))
        lcd.display_lcd_line2("Signal = " +  str(dbLevel))
        turn_leds_on(level)
    else:
        turn_leds_on(0)
        lcd.clear()
        lcd.display_lcd_line1("Out of Range")
        


Ejemplo n.º 6
0
def get_data():
    return iw_parse.get_interfaces(interface='wlan0')
Ejemplo n.º 7
0
def scan(interface="wlan0"):
    """
    Give the list of Access Points and Ad-Hoc cells in range.
    """

    return get_interfaces(interface=interface)
Ejemplo n.º 8
0
import iw_parse
networks = iw_parse.get_interfaces(interface='wlan0')
#print networks
for line in networks:
    print line
    print "------------------------------------------------------"
Ejemplo n.º 9
0
def runScan(retryCounter=0):
    """
    Runs a scan for obtaining router information such as IP and MAC addresses.
    Uses all methods to create a CSV file with obtained user requirements.
    NOTE: In order to run this program, you must:
        1. Call This file in terminal
        2. Use flags to set up program (add the flag '--help' or '-h' for additional information)
    
    Args:
        ''retryCounter'' (An integer): Used for recursive function calling.

    Raises:
        Exception: After 3 failed scan attemps, the program will stop.
        TypeError: If the signal limit flag is not specified with an integer value.
        ValueError: If the integer value is not specified within 0 - 100.

    Returns:
        A string of the file name.
    """
    # Initiliaze Parser and Commands
    parser = argparse.ArgumentParser(
        description='A WiFi Scanner parser used for file configurations')
    parser.add_argument("--fileName",
                        type=str,
                        required=True,
                        help="Used to name the output CSV file (Required)")
    parser.add_argument(
        "--sigLimit",
        type=int,
        default=50,
        help="Minimum signal strength requested (i.e. 50, 72, 90). Default = 50"
    )
    parser.add_argument("--verbose",
                        action="store_true",
                        help="Displays router info in the terminal")
    args = parser.parse_args()

    # Test for appropriate signal variable
    if (type(args.sigLimit) != int):
        raise TypeError("The signal requirement must be an integer value")
    if (args.sigLimit < 0 or args.sigLimit > 100):
        raise ValueError(
            "The signal requirement must be between 0 and 100, inclusive.")

    # Initialize Variables
    interface = 'wlp2s0'
    fileName = os.getcwd() + '/' + args.fileName + '.csv'
    stringList = []
    routerList = []
    refreshRate = 2  # Will wait this long (sec) before scanning again
    minRequiredRouters = 3  # How many routers do we need minimum?
    defaultListLength = 5
    routerListLen = len(routerList)

    # Stop running program after 3 attempts
    if (retryCounter > 3):
        raise Exception("Failed after 3 attempts")

    # Start Scans until fulfilled minimum router requirements
    print("Scanning, please wait...")
    while (routerListLen < minRequiredRouters):
        routerList = working_interface.get_interfaces(interface)
        routerListLen = len(routerList)
        time.sleep(refreshRate)
    print("\nScan completed")

    # Organize Data into lists and strings
    stringList = displayReq(routerList, args.sigLimit, args.verbose)
    routerList = stringToList(stringList, defaultListLength)

    # Write to CSV file
    writeToFile(routerList, fileName)

    # Check for appropriate data in CSV file
    try:
        with open(fileName, "r") as outputCSV:
            outputReader = csv.reader(outputCSV, delimiter=',')
            outputCount = -1  # Negative 1 for row header
            if (args.verbose):
                print("Found these rows in the file:")
            for row in outputReader:
                if (args.verbose):
                    print(row)
                outputCount += 1
            # Run operation again
            if (outputCount < minRequiredRouters):
                retryCounter += 1
                print("FAILED {} time(s)...".format(retryCounter))
                runScan(retryCounter)

    except:
        if (retryCounter > 3):
            print "Failed to find enough routers"
        else:
            print "This file does not exist"
    # Return file name
    return fileName