def showAP(self): """ Displays Access Points in Range""" print("Scanning APs - May take several seconds\n") scan = iwlist.scan("{}".format(PwnInterface)) # Set a timeout before Parsing, If there's multiple APs it may not find them all time.sleep(3) # Parse iwlist Output to a easily readable Dictionary parse = iwlist.parse(scan) # Clear AP List each time this function is called (ScanAP Button) self.ff.clear() try: for i in parse: item = gui.QStandardItem(str(i["essid"])) bssid = str(i["mac"]) essid = str(i["essid"]) channel = str(i["channel"]) encryption = str(i["encryption"]) item.setData(bssid, 256) item.setData(essid, 257) item.setData(channel, 258) item.setData(encryption, 259) self.ff.appendRow(item) except KeyError: print("KeyError") pass
def process_request(self, data): title = data['title'] contents = data['contents'] # Request for wifi connection status information if title == WIFI_STATUS: wifi_status_data = iwlist.check() self.server_sock.send(wifi_status_data) print("wifi connection status data was sent!") self.server_sock.close() elif title == WIFI_LIST: scan_data = iwlist.scan() self.server_sock.send(scan_data) print("iwlist data was sent!") self.server_sock.close() elif title == CONNECT_WIFI: SSID = contents["SSID"] PW = contents["PW"] result = iwlist.connect(SSID, PW) if len(result) == 0: self.server_sock.send(0) print("wifi connected with SSID : ", SSID) self.server_sock.close() # TODO: if wifi connected start face recognition # android should get face recognition state from server. else: print "Wrong request" return
def main(): pub = rospy.Publisher('wlanInfo', wlan, queue_size=10) rospy.Subscriber("camera_pose", PointStamped, callback) rospy.init_node('wifi', anonymous=True) rate = rospy.Rate(1) # 10hz filename = datetime.today().strftime('%Y-%m-%d-%H:%M:%S') f = open("WIFI-" + filename + ".txt", "w+") while not rospy.is_shutdown(): #start = time.time() content = iwlist.scan(interface='wlp7s0b1') cells = iwlist.parse(content) #end = time.time() #print("Sampling rate:", int(1/(end - start)), "Hz") now = rospy.Time.now() #time_stamp = str(now.secs + now.nsecs/10e9) rospy.loginfo("Timestamp %i sec %i nsec", now.secs, now.nsecs) print("Number of access points:", len(cells)) for i in range(len(cells)): temp = cells[i] essid = str(temp["essid"]) channel = str(temp["channel"]) mac_addr = str(temp["mac"]) frequency = str(temp["frequency"]) rss = str(temp["signal_level_dBm"]) f.write("WIFI;%i %i;%s;%s;%s;%s;%s\r\n" % (now.secs, now.nsecs, essid, channel, mac_addr, frequency, rss)) print("Point:", i + 1, "[INFO]", cells[i]) print("----------------------------------------------") rate.sleep() f.close()
def __get_wifi_networks_linux(): networks = [] scanned_networks = iwlist.parse( iwlist.scan(interface=__get_first_interface_linux())) for c_net in scanned_networks: networks.append({ "mac": c_net["mac"], "powrx": int(c_net["signal_level_dBm"]), "name": c_net["essid"] }) return networks
def getWiFiStrength(): content=iwlist.scan(interface='wlan0') cells=iwlist.parse(content) strength = 0 connectedwifi=getConnectedWifi() for cell in cells: if(str(cell['mac'])==connectedwifi): strength=int(cell["signal_quality"])*4/int(cell["signal_total"]) break #print(str(cell['mac']),connectedwifi,str(cell['mac'])==connectedwifi) #print(strength) return round(strength,1)
def scan_and_get_data(mac_whitelist=[]): """ Will scan all AP, filter out any that do not match the mac_whitelist, then return the data as a list of objects :param mac_whitelist: a list of mac addresses to white list the scan data :return: a list of scan data objects """ scan_timestamp = datetime.datetime.now() scan_content = iwlist.scan(interface='wlan0') # takes 3 or 4 seconds unfiltered_cells = parse_and_format(scan_content, scan_timestamp) filtered_cells = filter_mac(unfiltered_cells, mac_whitelist) formatted_scan_data = {"time": scan_timestamp, "cells": filtered_cells} return formatted_scan_data
def scan(s, loopTime): # Run iwlist to store all found wifi results into a list content = iwlist.scan() wifiList = iwlist.parse(content) # list containing objects with wifi data wifiFile = 'wifi_found.json' wifiJSON = [] #list to store updated results # Load json file if it already exists if os.path.isfile(wifiFile): with open(wifiFile) as jsonFile: wifiJSON = json.load(jsonFile) wifiListCount = len(wifiList) # Number of wifi connections found wifiJSONCount = len(wifiJSON) # Number of wifi connections stored # Loop through found networks for wi in range(wifiListCount): found = False # Loop through stored networks for wfi in range(wifiJSONCount): # Check if the wifi network id already exists if wifiList[wi]['essid'] == wifiJSON[wfi]['essid']: # Check if it shares the same mac address if wifiList[wi]['mac'] == wifiJSON[wfi]['mac']: found = True # Update it's signal strength if it's closer # and update it's timestamp if int(wifiList[wi]['signal_level']) < int( wifiJSON[wfi]['signal_level']): wifiJSON[wfi]['signal_level'] = wifiList[wi][ 'signal_level'] time = datetime.datetime.now().time() wifiJSON[wfi]['time'] = str(time) break # If it's a new network found add it to the list if found == False: wifiJSON.append(wifiList[wi]) # Overwrite the existing JSON file with the new list. writeJSONFile(wifiFile, wifiJSON) else: # Write original wifi list to JSON if no file exists. writeJSONFile(wifiFile, wifiList) # Loop through scan s.enter(loopTime, 1, scan, (s, loopTime))
def strength(): content = iwlist.scan(interface='wlan0') cells = iwlist.parse(content) signal = 0 for i in cells: if i["essid"].startswith("Catherine"): mac = i["mac"] signal = i["signal_level_dBm"] age = 0 break return signal
def getgeolocation(): print("computing geolocation....") content = iwlist.scan(interface='wlan0') cells = iwlist.parse(content) print(cells) request = unwiredlabs.UnwiredRequest() for cell in cells: request.addAccessPoint(cell['mac'], int(cell['signal_level_dBm'])) conn = unwiredlabs.UnwiredConnection(key=key) res = conn.performRequest(request) if (res.status != "Ok"): print("Error: ", res.status) else: gmaps = "https://maps.google.com/?q=" + str( res.coordinate[0]) + "," + str(res.coordinate[1]) print(gmaps) pubnub.publish(channel="your-pubnub-channel", message=gmaps)
def wifi_scan(q): delta = 0 while True: t_init = time.time() raw_results = iwlist.scan(interface=IFACE) #trigger a scan t_end = time.time() results = iwlist.parse(raw_results) jitter = (t_end - t_init) - delta delta = t_end - t_init q.put_nowait({ 'start': t_init, 'end': t_end, 'delta': delta, 'jitter': jitter, 'results': results }) pass pass
def callback(camera_pose): f.write("POSI;%i;%i;%f;%f;%f\r\n" % (camera_pose.header.stamp.secs, camera_pose.header.stamp.nsecs, camera_pose.point.x, camera_pose.point.y, camera_pose.point.z)) content = iwlist.scan(interface='wlp7s0b1') cells = iwlist.parse(content) now = rospy.Time.now() #rospy.loginfo("Timestamp %i sec %i nsec", now.secs, now.nsecs) print("Number of Access Points:", len(cells)) for i in range(len(cells)): temp = cells[i] essid = str(temp["essid"]) channel = str(temp["channel"]) mac_addr = str(temp["mac"]) frequency = str(temp["frequency"]) rss = str(temp["signal_level_dBm"]) f.write("WIFI;%i;%i;%s;%s;%s;%s;%s\r\n" % (now.secs, now.nsecs, essid, channel, mac_addr, frequency, rss)) #print("Point:", i+1, "[INFO]", cells[i]) #print("----------------------------------------------") print("----------------------------------------------")
def talker(): pub = rospy.Publisher('wlanInfo', wlan, queue_size=10) rospy.init_node('talker', anonymous=True) rate = rospy.Rate(10) # 10hz filename = datetime.today().strftime('%Y-%m-%d-%H:%M:%S') f = open("WIFI-" + filename + ".txt", "w+") while not rospy.is_shutdown(): msg = wlan() #start = time.time() content = iwlist.scan(interface='wlp7s0b1') cells = iwlist.parse(content) #end = time.time() #print("Sampling rate:", int(1/(end - start)), "Hz") now = rospy.Time.now() AppTimestamp = str(now.secs) + "." + str(now.nsecs / 10e9) rospy.loginfo("Timestamp %i sec %i nsec", now.secs, now.nsecs) print("Number of access points:", len(cells)) for i in range(len(cells)): temp = cells[i] essid = str(temp["essid"]) mac_addr = str(temp["mac"]) + ";" frequency = str(temp["frequency"]) rss = str(temp["signal_level_dBm"]) #if temp["mac"] == "1C:DE:A7:1B:0B:B1": msg.header.stamp = now msg.mac = temp["mac"] msg.signal_strength = int(temp["signal_level_dBm"]) pub.publish(msg) f.write("WIFI;%s;\r\n" % (AppTimestamp)) #print(mac["signal_level_dBm"]) #print("MAC Address:", cells[i].) print("Point:", i + 1, "[INFO]", cells[i]) #print(cells) print("----------------------------------------------") #time.sleep(1) rate.sleep()
def index(): if request.method == "GET": if win: ret = open( "C:\\Users\\61301765\\Documents\\shsb-pi\\wifiscan_result.txt" ).read() else: ret = scan() return render_template('index.html', wifiscan=parse(ret)) else: ssid = request.form['ssid'] pw = request.form['pw'] if not win: conf = open('/home/pi/conf.conf', 'a') else: conf = open( "C:\\Users\\61301765\\Documents\\shsb-captive-portal\\wpa-conf.txt", 'a') print(ssid, pw) conf.write('network={ssid=\"' + ssid + '\"psk=\"' + pw + '\"}') conf.close() return render_template('saved.html')
def main(): wot = iwlist.scan('wlp6s0') ssids = iwlist.parse(wot) pprint(ssids) channels = list(map(lambda s: int(s['channel']) , ssids)) signal_levels = list(map(lambda s: int(s['signal_level_dBm']) , ssids)) labels = list(map(lambda s: s['essid'] , ssids)) # x, y = ([8, 1, 2, 5, 8, 8, 9, 13, 13, 52, 52, 52], [-46, -84, -48, -60, -47, -47, -64, -69, -37, -45, -45, -45]) for x, y, label in zip(channels, signal_levels, labels): plt.plot([x-1.5, x-1, x+1, x+1.5], [-100, y, y, -100], label=label) plt.xlabel('x label') plt.ylabel('y label') plt.title("Simple Plot") plt.legend() plt.show()
def print_iwlist(self): while self.counter: if self.stopped: #self.name.exit() return # time.sleep(self.delay) start = time.time() """ Pretty prints the output of iwlist scan into a table. """ content = iwlist.scan(self.interface) #(interface='wlan0') self.cells = iwlist.parse(content) # print cells sortby = "signal_level_dBm" reverse = False self.cells.sort(None, lambda el: el[sortby], reverse) self.updated = True self.time_taken = time.time()-start self.counter -= 1 self.stopped = True return
# quit if a dir w/ .tsv files hasn't been provided if not args.output_dir: args.output_dir = '../data' # gps log file (0 buffering) filename = os.path.join(args.output_dir, 'wifi-log.csv') if os.path.exists(filename): wifi_log = csv.writer(open(filename, 'a', 0)) else: wifi_log = csv.writer(open(filename, 'wb+', 0)) wifi_log.writerow(attrs) while True: curr_timestamp = time.time() content = iwlist.scan(interface = 'wlan0') # content = "" # with open ("scan.txt", "r") as myfile: # content = myfile.read() cells = iwlist.parse(content) for cell in cells: # update the 'time' attr, accounting w/ the last_beacon component cell['time'] = int(curr_timestamp - float(cell['last_beacon']) / 1000.0) # write new row to .csv log wifi_log.writerow([cell[attr] for attr in attrs])
import iwlist import time import json arquivo = open('/home/ericlee/Downloads/banco_dados_dicionario', 'r') dados = json.load(arquivo) print(type(dados)) x = 1 while (x == 1): scan = iwlist.scan('wlps30') cell = iwlist.parse(scan) dict_chances = dict() for local in dados: chance = 0 for roteador in dados[local]: sinal = dados[local][roteador] time.sleep(2) print('aiai') x = 0 arquivo.close()
from time import sleep, gmtime, strftime import time, os import radioMap as radioMap import numpy as np from scipy.stats import mstats testDict = dict() for tries in range(1, 11): terminate = False while not terminate: print("----------------------Try " + str(tries) + "/10-------------------------------") content = iwlist.scan(interface='wlp3s0') cells = iwlist.parse(content) newDict = dict() newList = list() for dicts in cells: newDict = dict() newDict["Try"] = str(tries) for key, value in dicts.items(): if key == "mac": newDict["MAC Address"] = value if key == "signal_level_dBm": newDict["Signal Level"] = value if key == "cellnumber":
liste_bssid_w = [] liste_channels = [] print('QUELLE EST VOTRE CARTE RESEAU : ') liste = os.listdir('/sys/class/net') print(len(liste)) nbr = 1 for x in liste: print(str(nbr)+") "+x) nbr += 1 card = input('number : ') choice = input('Are you sure ? ('+liste[int(card)-1]+') [yes/no]') if choice == "yes": print('Choice the wifi for the attack') content = iwlist.scan(interface=liste[int(card)-1]) cells = iwlist.parse(content) nbr = 1 for x in cells: print(str(nbr)+') '+x['essid']) nbr += 1 liste_bssid_w.append(x['mac']) try: print(x['channel']) liste_channels.append(x['channel']) except: print('ERROR FOR THIS WIFI') u = input('number : ') wifi_fa = liste_bssid_w[int(u)-1] channel = liste_channels[int(u)-1] #obtention bssid
if (len(sys.argv) != 3): print "Usage: " + sys.argv[0] + " ZoneName " + "SampleNumber" exit() zoneName = sys.argv[1] try: sampleNumber = int(sys.argv[2]) except: print "Non valid sample number" exit() res = [] for i in range(sampleNumber): print "Scanning " + str(i + 1) + "/" + str(sampleNumber) content = iwlist.scan(interface=INTERFACE) cells = iwlist.parse(content) for el in cells: for field in FIELD_TO_IGNORE: el.pop(field, None) # Corrupted data with positive dBm for sample in cells: if int(sample['signal_level_dBm']) > 0: print 'Adjusting corrupted dBm' sample['signal_level_dBm'] = "-100" obj = {} obj['scan'] = cells obj['zone'] = zoneName
import iwlist import json arquivor = open('/home/ericlee/Downloads/banco_dados_dicionario','r') scan = iwlist.scan('wlp3s0') cell = iwlist.parse(scan) dicionario=json.load(arquivor) arquivor.close() arquivow = open('/home/ericlee/Downloads/banco_dados_dicionario','w') local = raw_input('Insira o nome do local medido: ') if local in dicionario: for i in cell: if i['mac'] in dicionario[local]: dicionario[local][i['mac']].append(int(i['db'])) else: dicionario[local][i['mac']] = [int(i['db'])] else: dicionario[local]=dict() for i in cell: dicionario[local][i['mac']] = [int(i['db'])]
def grepWifi(): content = iwlist.scan() wifis = iwlist.parse(content) return wifis
# -*- coding: utf-8 -*- import iwlist import json from time import sleep arquivo = open('banco_dados_dicionario', 'r') dict_dados = json.load(arquivo) x = 1 while (x == 1): escaneamento = iwlist.scan('wlp3s0') cell = iwlist.parse(escaneamento) dict_scan = dict() for roteador in cell: dict_scan[str(roteador['mac'])] = int(roteador['db']) dict_pts = dict() for local in dict_dados: pontos_local = 0 for rot_scan in dict_scan: if rot_scan not in dict_dados[local]: pontos_local += -1
'00:0B:86:96:82:20', '00:0B:86:96:61:C0', '70:70:8B:09:2F:E0', '00:1D:AA:0F:7C:44', 'AC:9E:17:7E:E6:38', 'B8:A3:86:57:17:67', 'EA:9E:B4:2D:81:32' ] param_each_ap = ['SIG_Q', 'SIG_L', 'NOISE_L'] repeat_num = 3 repeat_interval = 1 curr_repeat_idx = 0 raw_data = [] while curr_repeat_idx < repeat_num: raw_datum = [ 0.0 ] * len(interface_names) * len(picked_mac) * len(param_each_ap) for ifn_idx, ifn in enumerate(interface_names): cells = iwlist.parse(iwlist.scan(interface=ifn)) for cell in cells: if (cell['mac'] in picked_mac): idx = picked_mac.index(cell['mac']) raw_datum[ifn_idx * len(picked_mac) * len(param_each_ap) + idx * len(param_each_ap)] = float( cell['signal_quality']) if (' ' in cell['signal_level_dBm']): raw_datum[ifn_idx * len(picked_mac) * len(param_each_ap) + idx * len(param_each_ap) + 1] = float( cell['signal_level_dBm'] [:cell['signal_level_dBm'].index(' ')]) raw_datum[ifn_idx * len(picked_mac) * len(param_each_ap) + idx * len(param_each_ap) + 2] = float( cell['signal_level_dBm'] [cell['signal_level_dBm'].index('=') + 1:])