コード例 #1
0
    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
コード例 #2
0
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()
コード例 #3
0
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
コード例 #4
0
ファイル: test.py プロジェクト: ydxt25/python-iwlist
 def setUp(self):
     dirs = os.listdir("test")
     self.cases = []
     for d in dirs:
         scanFile = os.path.join("test", d, "scan.txt")
         vectorsFile = os.path.join("test", d, "vectors.json")
         case = {
             "name": d,
             "parsed": iwlist.parse(fileContent(scanFile)),
             "expected": json.loads(fileContent(vectorsFile)),
         }
         self.cases.append(case)
コード例 #5
0
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)
コード例 #6
0
ファイル: test.py プロジェクト: iancoleman/python-iwlist
 def setUp(self):
     dirs = os.listdir("test")
     self.cases = []
     for d in dirs:
         scanFile = os.path.join("test", d, "scan.txt")
         vectorsFile = os.path.join("test", d, "vectors.json")
         case = {
                 "name": d,
                 "parsed": iwlist.parse(fileContent(scanFile)),
                 "expected": json.loads(fileContent(vectorsFile)),
             }
         self.cases.append(case)
コード例 #7
0
ファイル: wifihunter.py プロジェクト: csmets/wifihunter
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))
コード例 #8
0
ファイル: wifi_phone.py プロジェクト: samariewilson/SPE2018
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
コード例 #9
0
ファイル: test.py プロジェクト: UC-Senior-Design/Main-Repo
def parse_and_format(scan_content, scan_timestamp):
    """
    Given raw scan content from iwlist.parse(), will parse it into a known object with distance calculations
    :param scan_timestamp: time of scan
    :param scan_content: raw scan content
    :return: formatted scan data
    """
    parsed_cells = iwlist.parse(scan_content)
    for cell in parsed_cells:
        if "frequency" in cell:
            cell["distance"] = {
                "raw": convert_rssi_to_meters(float(cell["signal_level_dBm"])),
                "kalman": -1.0
            }  # todo kalman
            cell["time"] = scan_timestamp
    return parsed_cells
コード例 #10
0
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)
コード例 #11
0
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
コード例 #12
0
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("----------------------------------------------")
コード例 #13
0
ファイル: app.py プロジェクト: jobsorrow/shsb-captive-portal
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')
コード例 #14
0
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()
コード例 #15
0
ファイル: ssidplot.py プロジェクト: not7cd/ssidplot
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()    
コード例 #16
0
    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
コード例 #17
0
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()
コード例 #18
0
def grepWifi():
    content = iwlist.scan()
    wifis = iwlist.parse(content)
    return wifis
コード例 #19
0
		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 choi == 1:
コード例 #20
0
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":
                    newDict["Cell Number"] = value
コード例 #21
0
 def setUp(self):
     self.parsed = iwlist.parse(open("test/scan.txt").read())
     self.expected = json.loads(open("test/vectors.json").read())
コード例 #22
0
ファイル: predict.py プロジェクト: tom6311tom6311/IOTProject2
    '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:])
コード例 #23
0
# -*- 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