Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python
- # Mooi script blablabal
- # Import the necessary packages
- import argparse
- import mysql.connector as mariadb
- import time
- import re
- import subprocess
- __author__ = 'H.Vogd, R.Engelbertink'
- __date__ = '20190420'
- __version__ = '1.0'
- # Declare static variables
- VERSION_RGX = re.compile("version\s+\d+", re.IGNORECASE)
- DB_HOST = '192.168.19.131'
- DB_USER = 'root'
- DB_PASSWORD = '123querty'
- DB_DATABASE = 'details'
- # Read commandline arguments
- ap = argparse.ArgumentParser()
- ap.add_argument('int', default="wlan0",
- help='Specify interface to use. Default is wlan0')
- args = vars(ap.parse_args())
- # Create non-array variables with values of commandline argument
- interface = args['int']
- # Declare functions to
- def matching_line(lines, keyword):
- """ Returns the first matching line in a list of lines.
- @see match()
- """
- for line in lines:
- matching = match(line, keyword)
- if matching != None:
- return matching
- return None
- def match(line, keyword):
- """ If the first part of line (modulo blanks) matches keyword,
- returns the end of that line. Otherwise checks if keyword is
- anywhere in the line and returns that section, else returns None"""
- line = line.lstrip()
- length = len(keyword)
- if line[:length] == keyword:
- return line[length:]
- else:
- if keyword in line:
- return line[line.index(keyword):]
- else:
- return None
- # Extract ESSID from cell
- def get_name(cell):
- essid = matching_line(cell, "ESSID:")
- if not essid:
- return ""
- return essid[1:-1]
- # Extract Signal Quality from cell
- def get_quality(cell):
- quality = matching_line(cell, "Quality=")
- if quality is None:
- return ""
- quality = quality.split()[0].split("/")
- quality = matching_line(cell, "Quality=").split()[0].split("/")
- return str(int(round(float(quality[0]) / float(quality[1]) * 100)))
- # Extract Signal Level from cell
- def get_signal_level(cell):
- signal = matching_line(cell, "Signal level=")
- if signal is None:
- return ""
- signal = signal.split("=")[1].split("/")
- if len(signal) == 2:
- return str(int(round(float(signal[0]) / float(signal[1]) * 100)))
- elif len(signal) == 1:
- return signal[0].split(' ')[0]
- else:
- return ""
- # Extract Channel from cell
- def get_channel(cell):
- channel = matching_line(cell, "Channel:")
- if channel:
- return channel
- frequency = matching_line(cell, "Frequency:")
- channel = re.sub(r".*\(Channel\s(\d{1,3})\).*", r"\1", frequency)
- return channel
- # Extract Frequency from cell
- def get_frequency(cell):
- frequency = matching_line(cell, "Frequency:")
- if frequency is None:
- return ""
- return frequency.split()[0]
- # Extract Enqryption type from cell
- def get_encryption(cell, emit_version=False):
- enc = ""
- if matching_line(cell, "Encryption key:") == "off":
- enc = "Open"
- else:
- for line in cell:
- matching = match(line, "IE:")
- if matching == None:
- continue
- wpa = match(matching, "WPA")
- if wpa == None:
- continue
- version_matches = VERSION_RGX.search(wpa)
- if len(version_matches.regs) == 1:
- version = version_matches \
- .group(0) \
- .lower() \
- .replace("version", "") \
- .strip()
- wpa = wpa.replace(version_matches.group(0), "").strip()
- if wpa == "":
- wpa = "WPA"
- if emit_version:
- enc = "{0} v.{1}".format(wpa, version)
- else:
- enc = wpa
- if wpa == "WPA2":
- return enc
- else:
- enc = wpa
- if enc == "":
- enc = "WEP"
- return enc
- # Extract MAC Address from cell
- def get_address(cell):
- return matching_line(cell, "Address: ")
- print(""" __ __.__ .__ ________ __ .__ .__
- / \ / \__|______ ____ | | ____ ______ ______ / _____/_____ _/ |_| |__ ___________|__| ____ ____
- \ \/\/ / \_ __ \_/ __ \| | _/ __ \ / ___// ___/ / \ ___\__ \\ __\ | \_/ __ \_ __ \ |/ \ / ___\
- \ /| || | \/\ ___/| |_\ ___/ \___ \ \___ \ \ \_\ \/ __ \| | | Y \ ___/| | \/ | | \/ /_/ >
- \__/\ / |__||__| \___ >____/\___ >____ >____ > \______ (____ /__| |___| /\___ >__| |__|___| /\___ /
- \/ \/ \/ \/ \/ \/ \/ \/ \/ \//_____/ """)
- #Open database connection
- mariadb_connection = mariadb.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, database=DB_DATABASE)
- # Run bash command to scan for AP's. Change format to STDOUT
- iw_output = subprocess.check_output(['iwlist', interface, 'scanning']).decode('utf-8').split('\n')
- # Record current time
- now = time.strftime('%Y-%m-%d %H:%M:%S')
- # Define values to extract from iw_output
- rules = {
- "Name": get_name,
- "Quality": get_quality,
- "Channel": get_channel,
- "Frequency": get_frequency,
- "Encryption": get_encryption,
- "Address": get_address,
- "Signal Level": get_signal_level,
- }
- # Parse cells with the value from iw_output
- cells = [[]]
- parsed_cells = []
- for line in iw_output:
- cell_line = match(line, "Cell ")
- if cell_line != None:
- cells.append([])
- line = cell_line[-27:]
- cells[-1].append(line.rstrip())
- cells = cells[1:]
- for cell in cells:
- parsed_cell = {}
- for key in rules:
- rule = rules[key]
- parsed_cell.update({key: rule(cell)})
- parsed_cells.append(parsed_cell)
- # Insert scan results in sql database
- for ap in parsed_cells:
- # Assign all variables in a tuple for the VALUES part of the SQL-query
- values = (ap['Address'], ap['Signal Level'], ap['Name'], ap['Encryption'], ap['Channel'], now)
- # Prepare query
- sql_insert_query = """ INSERT INTO `details`
- (`macaddress`,`signalstrength`,`ssid`,`security`,`wifichannel`,`timestamp`) VALUES (%s, %s, %s, %s, %s, %s)"""
- # Execute query
- cursor = mariadb_connection.cursor() #connect to execute query
- result = cursor.execute(sql_insert_query, values) #execute the SQL query with the assigned vars
- mariadb_connection.commit() #commit to server
- print("Record inserted successfully, containing the following information: \n" + str(values)) #feedback in term
- # Close the connection for security purposes when done
- if (mariadb_connection.is_connected()):
- cursor.close()
- mariadb_connection.close()
- print(" Connection is closed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement