Advertisement
Guest User

Untitled

a guest
Apr 17th, 2019
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.88 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3. # Mooi script blablabal
  4.  
  5. # Import the necessary packages
  6. import argparse
  7. import mysql.connector as mariadb
  8. import time
  9. import re
  10. import subprocess
  11.  
  12. __author__ = 'H.Vogd, R.Engelbertink'
  13. __date__ = '20190420'
  14. __version__ = '1.0'
  15.  
  16. # Declare static variables
  17. VERSION_RGX = re.compile("version\s+\d+", re.IGNORECASE)
  18. DB_HOST = '192.168.19.131'
  19. DB_USER = 'root'
  20. DB_PASSWORD = '123querty'
  21. DB_DATABASE = 'details'
  22.  
  23. # Read commandline arguments
  24. ap = argparse.ArgumentParser()
  25. ap.add_argument('int', default="wlan0",
  26. help='Specify interface to use. Default is wlan0')
  27. args = vars(ap.parse_args())
  28.  
  29. # Create non-array variables with values of commandline argument
  30. interface = args['int']
  31.  
  32. # Declare functions to
  33. def matching_line(lines, keyword):
  34. """ Returns the first matching line in a list of lines.
  35. @see match()
  36. """
  37. for line in lines:
  38. matching = match(line, keyword)
  39. if matching != None:
  40. return matching
  41. return None
  42.  
  43.  
  44. def match(line, keyword):
  45. """ If the first part of line (modulo blanks) matches keyword,
  46. returns the end of that line. Otherwise checks if keyword is
  47. anywhere in the line and returns that section, else returns None"""
  48.  
  49. line = line.lstrip()
  50. length = len(keyword)
  51. if line[:length] == keyword:
  52. return line[length:]
  53. else:
  54. if keyword in line:
  55. return line[line.index(keyword):]
  56. else:
  57. return None
  58.  
  59.  
  60. # Extract ESSID from cell
  61. def get_name(cell):
  62. essid = matching_line(cell, "ESSID:")
  63. if not essid:
  64. return ""
  65. return essid[1:-1]
  66.  
  67.  
  68. # Extract Signal Quality from cell
  69. def get_quality(cell):
  70. quality = matching_line(cell, "Quality=")
  71. if quality is None:
  72. return ""
  73. quality = quality.split()[0].split("/")
  74. quality = matching_line(cell, "Quality=").split()[0].split("/")
  75. return str(int(round(float(quality[0]) / float(quality[1]) * 100)))
  76.  
  77.  
  78. # Extract Signal Level from cell
  79. def get_signal_level(cell):
  80. signal = matching_line(cell, "Signal level=")
  81. if signal is None:
  82. return ""
  83. signal = signal.split("=")[1].split("/")
  84. if len(signal) == 2:
  85. return str(int(round(float(signal[0]) / float(signal[1]) * 100)))
  86. elif len(signal) == 1:
  87. return signal[0].split(' ')[0]
  88. else:
  89. return ""
  90.  
  91.  
  92. # Extract Channel from cell
  93. def get_channel(cell):
  94. channel = matching_line(cell, "Channel:")
  95. if channel:
  96. return channel
  97. frequency = matching_line(cell, "Frequency:")
  98. channel = re.sub(r".*\(Channel\s(\d{1,3})\).*", r"\1", frequency)
  99. return channel
  100.  
  101.  
  102. # Extract Frequency from cell
  103. def get_frequency(cell):
  104. frequency = matching_line(cell, "Frequency:")
  105. if frequency is None:
  106. return ""
  107. return frequency.split()[0]
  108.  
  109.  
  110. # Extract Enqryption type from cell
  111. def get_encryption(cell, emit_version=False):
  112. enc = ""
  113. if matching_line(cell, "Encryption key:") == "off":
  114. enc = "Open"
  115. else:
  116. for line in cell:
  117. matching = match(line, "IE:")
  118. if matching == None:
  119. continue
  120.  
  121. wpa = match(matching, "WPA")
  122. if wpa == None:
  123. continue
  124.  
  125. version_matches = VERSION_RGX.search(wpa)
  126. if len(version_matches.regs) == 1:
  127. version = version_matches \
  128. .group(0) \
  129. .lower() \
  130. .replace("version", "") \
  131. .strip()
  132. wpa = wpa.replace(version_matches.group(0), "").strip()
  133. if wpa == "":
  134. wpa = "WPA"
  135. if emit_version:
  136. enc = "{0} v.{1}".format(wpa, version)
  137. else:
  138. enc = wpa
  139. if wpa == "WPA2":
  140. return enc
  141. else:
  142. enc = wpa
  143. if enc == "":
  144. enc = "WEP"
  145. return enc
  146.  
  147.  
  148. # Extract MAC Address from cell
  149. def get_address(cell):
  150. return matching_line(cell, "Address: ")
  151.  
  152. print(""" __ __.__ .__ ________ __ .__ .__
  153. / \ / \__|______ ____ | | ____ ______ ______ / _____/_____ _/ |_| |__ ___________|__| ____ ____
  154. \ \/\/ / \_ __ \_/ __ \| | _/ __ \ / ___// ___/ / \ ___\__ \\ __\ | \_/ __ \_ __ \ |/ \ / ___\
  155. \ /| || | \/\ ___/| |_\ ___/ \___ \ \___ \ \ \_\ \/ __ \| | | Y \ ___/| | \/ | | \/ /_/ >
  156. \__/\ / |__||__| \___ >____/\___ >____ >____ > \______ (____ /__| |___| /\___ >__| |__|___| /\___ /
  157. \/ \/ \/ \/ \/ \/ \/ \/ \/ \//_____/ """)
  158.  
  159. #Open database connection
  160. mariadb_connection = mariadb.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, database=DB_DATABASE)
  161.  
  162. # Run bash command to scan for AP's. Change format to STDOUT
  163. iw_output = subprocess.check_output(['iwlist', interface, 'scanning']).decode('utf-8').split('\n')
  164.  
  165. # Record current time
  166. now = time.strftime('%Y-%m-%d %H:%M:%S')
  167.  
  168. # Define values to extract from iw_output
  169. rules = {
  170. "Name": get_name,
  171. "Quality": get_quality,
  172. "Channel": get_channel,
  173. "Frequency": get_frequency,
  174. "Encryption": get_encryption,
  175. "Address": get_address,
  176. "Signal Level": get_signal_level,
  177. }
  178.  
  179. # Parse cells with the value from iw_output
  180. cells = [[]]
  181. parsed_cells = []
  182.  
  183. for line in iw_output:
  184. cell_line = match(line, "Cell ")
  185. if cell_line != None:
  186. cells.append([])
  187. line = cell_line[-27:]
  188. cells[-1].append(line.rstrip())
  189.  
  190. cells = cells[1:]
  191.  
  192. for cell in cells:
  193. parsed_cell = {}
  194. for key in rules:
  195. rule = rules[key]
  196. parsed_cell.update({key: rule(cell)})
  197.  
  198. parsed_cells.append(parsed_cell)
  199.  
  200. # Insert scan results in sql database
  201. for ap in parsed_cells:
  202.  
  203. # Assign all variables in a tuple for the VALUES part of the SQL-query
  204. values = (ap['Address'], ap['Signal Level'], ap['Name'], ap['Encryption'], ap['Channel'], now)
  205.  
  206. # Prepare query
  207. sql_insert_query = """ INSERT INTO `details`
  208. (`macaddress`,`signalstrength`,`ssid`,`security`,`wifichannel`,`timestamp`) VALUES (%s, %s, %s, %s, %s, %s)"""
  209.  
  210. # Execute query
  211. cursor = mariadb_connection.cursor() #connect to execute query
  212. result = cursor.execute(sql_insert_query, values) #execute the SQL query with the assigned vars
  213. mariadb_connection.commit() #commit to server
  214.  
  215. print("Record inserted successfully, containing the following information: \n" + str(values)) #feedback in term
  216.  
  217. # Close the connection for security purposes when done
  218. if (mariadb_connection.is_connected()):
  219. cursor.close()
  220. mariadb_connection.close()
  221. print(" Connection is closed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement