def show_entries():
    """
    show wifi entries
    """
    wifi = Wireless('wlan0')
    essid = wifi.getEssid()
    return render_template('home.html', message=essid)
예제 #2
0
def checkwifi():
    #here is some trickery to work in windows
    #without making a cmd window pop up frequently
    startupinfo = None
    print "os.name=="+OSName
    if OSName == 'nt' or OSName =="win32": #the user is using windows so we don't want cmd to show
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        output = subprocess.Popen(["ipconfig", "/all"], stdout=subprocess.PIPE,
                                  startupinfo=startupinfo).communicate()[0]
        e=0
        lines=output.split('\n')
        for line in lines:
            if line.startswith('   Connection-specific DNS Suffix  . : '):
                if not len(line)==40:
                    nline=line[39:]
                    print(line)
                    if "dublinschool.org" in nline:
                        if(not lines[e-3].startswith('Tunnel')): #make sure this is not a tunnel adapter
                            print('found')
                            return(True)
            e=e+1; #maybe cleanup later
    elif SYSPlat == 'linux2':
        from pythonwifi.iwlibs import Wireless
        wifi = Wireless('wlan0')
        if(wifi.getEssid()=="student"):
            return(True)
예제 #3
0
	def collectDataForInterface(self, iface):
		w = Wireless(iface)
		wsconfig = { }

		simpleConfigs = (
			("essid",       w.getEssid,      "off"),
			("frequency",   w.getFrequency,  ""),
			("accesspoint", w.getAPaddr,     "Not-Associated"),
			("bitrate",     w.getBitrate,    "0"),
			("encryption",  w.getEncryption, "off"),
		)

		for name, func, default in simpleConfigs:
			try:
				wsconfig[name] = func()
			except:
				wsconfig[name] = default
		try:
			wsconfig["quality"] = str(Iwstats("wlan0").qual.quality) + "/" + str(w.getQualityMax().quality)
		except:
			wsconfig["quality"] = ""
		try:
			wsconfig["signal"] = str(w.getQualityAvg().siglevel-128) + " dBm"
		except:
			wsconfig["signal"] = ""

		return wsconfig
예제 #4
0
def main():
    rospy.init_node('wifi_poller')
    poll_freq = rospy.get_param('~poll_freq', 1)
    interface = rospy.get_param('~interface', 'eth1')
    frame_id = rospy.get_param('~frame_id', 'base_link')

    pub = rospy.Publisher('wifi_info', WifiInfo)

    wifi = Wireless(interface)
    poll_rate = rospy.Rate(poll_freq)
    while not rospy.is_shutdown():
        info = WifiInfo()
        info.header.stamp = rospy.Time.now()
        info.header.frame_id = frame_id

        try:
            info.essid = wifi.getEssid()
            info.interface = interface
            info.status = WifiInfo.STATUS_DISCONNECTED
            if info.essid:
                info.frequency = float(wifi.getFrequency().split(' ')[0])
                info.APaddr = wifi.getAPaddr()
                info.status = WifiInfo.STATUS_CONNECTED
        except IOError:
            # This can happen with an invalid iface
            info.status = WifiInfo.STATUS_ERROR
        except Exception, e:
            info.status = WifiInfo.STATUS_ERROR
            rospy.logerr('Error: %s' % e)

        pub.publish(info)
        poll_rate.sleep()
예제 #5
0
    def __init__(self, odoo, hardware):
        self.card = False  # currently swipped card code

        self.Odoo = odoo
        self.Buzz = hardware[0]  # Passive Buzzer
        self.Disp = hardware[1]  # Display
        self.Reader = hardware[2]  # Card Reader

        self.wifi = False
        self.wifi_con = Wireless('wlan0')

        self.card_logging_time_min = 1.5
        # minimum amount of seconds allowed for
        # the card logging process
        # making this time smaller means the terminal
        # is sooner ready to process the next card
        # making this time bigger allows
        # the user more time to read the message
        # shown in the display

        self.msg = False
        # Message that is used to Play a Melody or
        # Display which kind of Event happened: for example check in,
        # check out, communication with odoo not possible ...

        self.can_connect = odoo.can_connect

        self.minutes = 99
        self.checkodoo_wifi = True
        self.odoo_m = " "
        self.wifi_m = " "
        _logger.debug("Clocking Class Initialized")
예제 #6
0
    def collectDataForInterface(self, iface):
        w = Wireless(iface)
        wsconfig = {}

        simpleConfigs = (
            ("essid", w.getEssid, "off"),
            ("frequency", w.getFrequency, ""),
            ("accesspoint", w.getAPaddr, "Not-Associated"),
            ("bitrate", w.getBitrate, "0"),
            ("encryption", w.getEncryption, "off"),
        )

        for name, func, default in simpleConfigs:
            try:
                wsconfig[name] = func()
            except:
                wsconfig[name] = default
        try:
            wsconfig["quality"] = str(
                Iwstats("wlan0").qual.quality) + "/" + str(
                    w.getQualityMax().quality)
        except:
            wsconfig["quality"] = ""
        try:
            wsconfig["signal"] = str(w.getQualityAvg().siglevel - 128) + " dBm"
        except:
            wsconfig["signal"] = ""

        return wsconfig
def sniff_wifi():
    if plat == "OSX":
        # bridge to objective c(apple stuff)
        objc.loadBundle(
            "CoreWLAN", bundle_path="/System/Library/Frameworks/CoreWLAN.framework", module_globals=globals()
        )

        for iname in CWInterface.interfaceNames():
            interface = CWInterface.interfaceWithName_(iname)
            wifi_parameters = (
                "Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s, RSSI:           %s"
                % (iname, interface.ssid(), interface.transmitRate(), interface.transmitPower(), interface.rssi())
            )
    elif plat == "LINUX":
        interface = Wireless("wlan0")

        # Link Quality, Signal Level and Noise Level line
        wifi_parameters = "Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s" % (
            "wlan0",
            interface.getEssid(),
            interface.getBitrate(),
            interface.getTXPower(),
        )

    # record wifi parameters
    print wifi_parameters
    open(channels_file, "a").write(wifi_parameters + "\n")
예제 #8
0
def main():
    # if only program name is given, print usage info
    if len(sys.argv) == 1:
        usage()

    # if program name and one argument are given
    if len(sys.argv) == 2:
        option = sys.argv[1]
        # look for matching command
        list_command = get_matching_command(option)
        # if the one argument is a command
        if list_command is not None:
            for ifname in getNICnames():
                wifi = Wireless(ifname)
                list_command(wifi)
        else:
            print("iwlist.py: unknown command `%s' " \
                  "(check 'iwlist.py --help')." % (option, ))

    # if program name and more than one argument are given
    if len(sys.argv) > 2:
        # Get the interface and command from command line
        ifname, option = sys.argv[1:]
        # look for matching command
        list_command = get_matching_command(option)
        # if the second argument is a command
        if list_command is not None:
            wifi = Wireless(ifname)
            list_command(wifi, sys.argv[3:])
        else:
            print("iwlist.py: unknown command `%s' " \
                   "(check 'iwlist.py --help')." % (option, ))
예제 #9
0
def get_targets(w_nic):
    wifi = Wireless(w_nic)
    ap_list = wifi.scan()
    ap_targets = []
    for ap in wifi.scan():
        ap_targets.append(ap.essid[4:].strip().replace('\x00', ''))
        # This is becase we are running on a 64bit OS. A little hacky, but it works.
    return ap_targets
예제 #10
0
파일: wlan.py 프로젝트: 20after4/qtile
 def get_status(interface):
     interface = Wireless(interface)
     try:
         stats = Iwstats(interface)
     except IOError:
         return (None, None)
     quality = stats.qual.quality
     essid = interface.getEssid()
     return (essid, quality)
예제 #11
0
 def get_status(interface_name):
     interface = Wireless(interface_name)
     try:
         stats = Iwstats(interface_name)
     except IOError:
         return None, None
     quality = stats.qual.quality
     essid = interface.getEssid()
     return essid, quality
예제 #12
0
    def _poll_nic(self, ts, nicname):
        """
        Poll one NIC

        :param ts: data timestamp
        :type ts: int
        :param nicname: NIC name
        :type nicname: str
        :return: data list of metric 3-tuples (name, value, timestamp)
        :rtype: ``list``
        """
        stats = [('%s.associated' % nicname, 1, ts)]
        logger.debug('Polling NIC: %s', nicname)
        wifi = Wireless(nicname)
        if wifi.getAPaddr() == '00:00:00:00:00:00':
            # unassociated; return that one stat now
            logger.warning('%s not associated (AP address 00:00:00:00:00:00',
                           nicname)
            return [('%s.associated' % nicname, 0, ts)]
        # tx power
        try:
            txpwr = wifi.wireless_info.getTXPower().value
        except IOError:
            try:
                txpwr = wifi.getTXPower().split(' ')[0]
            except IOError:
                logger.debug('Could not get TX Power for %s', nicname)
                txpwr = None
        if txpwr is not None:
            stats.append(('%s.txpower_dbm' % nicname, txpwr, ts))
        # bitrate
        try:
            br = wifi.wireless_info.getBitrate().value
            stats.append(('%s.bitrate' % nicname, br, ts))
        except Exception:
            logger.warning('Could not get birtate for %s', nicname, exc_info=1)
        # RTS
        try:
            rts = wifi.wireless_info.getRTS().value
            stats.append(('%s.rts' % nicname, rts, ts))
        except Exception:
            logger.warning('Could not get RTS for %s', nicname, exc_info=1)
        # statistics
        try:
            s = Iwstats(nicname)
            for k in s.discard.keys():
                stats.append(
                    ('%s.discard_%s' % (nicname, k), s.discard.get(k, 0), ts))
            stats.append(('%s.missed_beacons' % nicname, s.missed_beacon, ts))
            # Current Quality
            stats.append(('%s.quality' % nicname, s.qual.quality, ts))
            stats.append(('%s.noise_level' % nicname, s.qual.nlevel, ts))
            stats.append(('%s.signal_level' % nicname, s.qual.siglevel, ts))
        except Exception:
            logger.warning('Could not get stats for %s', nicname, exc_info=1)
        return stats
예제 #13
0
def hijack_drone(target_ssid, interface):
    print('Hijacking {} using {}'.format(target_ssid, interface))
    os.system('ifconfig {} down'.format(interface))
    wifi = Wireless(interface)
    wifi.setEssid(target_ssid)
    os.system(
        'ifconfig {} 192.168.1.76 netmask 255.255.255.0'.format(interface))
    os.system('ifconfig {} up'.format(interface))
    os.system('route add -net 192.168.1.0 netmask 255.255.255.0')
    print('Hijack Networking complete')
예제 #14
0
파일: wlan.py 프로젝트: srynot4sale/qtile
 def update(self):
     interface = Wireless(self.interface)
     stats = Iwstats(self.interface)
     quality = stats.qual.quality
     essid = interface.getEssid()
     text = "{} {}/70".format(essid, quality)
     if self.text != text:
         self.text = text
         self.bar.draw()
     return True
예제 #15
0
파일: wlan.py 프로젝트: Cadair/qtile
 def update(self):
     interface = Wireless(self.interface)
     stats = Iwstats(self.interface)
     quality = stats.qual.quality
     essid = interface.getEssid()
     text = "{} {}/70".format(essid, quality)
     if self.text != text:
         self.text = text
         self.bar.draw()
     return True
    def getStatus(self):
        ifobj = Wireless(self.iface)
        fq = Iwfreq()
        try:
            self.channel = str(fq.getChannel(str(ifobj.getFrequency()[0:-3])))
        except:
            self.channel = 0
        status = {
            'BSSID':
            str(ifobj.getAPaddr()),  #ifobj.getStatistics()
            'ESSID':
            str(ifobj.getEssid()),
            'quality':
            "%s/%s" %
            (ifobj.getStatistics()[1].quality, ifobj.getQualityMax().quality),
            'signal':
            str(ifobj.getStatistics()[1].siglevel - 0x100) + " dBm",
            'bitrate':
            str(ifobj.getBitrate()),
            'channel':
            str(self.channel),
            #'channel': str(fq.getChannel(str(ifobj.getFrequency()[0:-3]))),
        }

        for (key, item) in status.items():
            if item is "None" or item is "":
                status[key] = _("N/A")

        return status
예제 #17
0
def main():

    
  frequency_channel_map = {
  2412000000: "1",
  2417000000: "2",
  2422000000: "3",
  2427000000: "4",
  2432000000: "5",
  2437000000: "6",
  2442000000: "7",
  2447000000: "8",
  2452000000: "9",
  2457000000: "10",
  2462000000: "11",
  2467000000: "12",
  2472000000: "13",
  2484000000: "14",
  5180000000: "36",
  5200000000: "40",
  5220000000: "44",
  5240000000: "48",
  5260000000: "52",
  5280000000: "56",
  5300000000: "60",
  5320000000: "64",
  5500000000: "100",
  5520000000: "104",
  5540000000: "108",
  5560000000: "112",
  5580000000: "116",
  5600000000: "120",
  5620000000: "124",
  5640000000: "128",
  5660000000: "132",
  5680000000: "136",
  5700000000: "140",
  5735000000: "147",
  5755000000: "151",
  5775000000: "155",
  5795000000: "159",
  5815000000: "163",
  5835000000: "167",
  5785000000: "171",
  }

  wifi = Wireless(iface)
  for ap in wifi.scan():
    print "SSID: {}".format(ap.essid)
    print "AP: ".format(ap.bssid)
    print "Signal: ".format(ap.quality.getSignallevel())
    print "Frequency: ".format((ap.frequency.getFrequency()))
    print "Channel:".format(frequency_channel_map.get(ap.frequency.getFrequency()))
    print ""
예제 #18
0
파일: wlan.py 프로젝트: Davidbrcz/qtile
 def poll(self):
     interface = Wireless(self.interface)
     try:
         stats = Iwstats(self.interface)
         quality = stats.qual.quality
         essid = interface.getEssid()
         return "{} {}/70".format(essid, quality)
     except IOError:
         logging.getLogger('qtile').error('%s: Probably your wlan device '
                 'is switched off or otherwise not present in your system.',
                 self.__class__.__name__)
예제 #19
0
 def poll(self):
     interface = Wireless(self.interface)
     try:
         stats = Iwstats(self.interface)
         quality = stats.qual.quality
         essid = interface.getEssid()
         return "{} {}/70".format(essid, quality)
     except IOError:
         logging.getLogger('qtile').error('%s: Probably your wlan device '
                 'is switched off or otherwise not present in your system.',
                 self.__class__.__name__)
예제 #20
0
def status(iface):
    """
    retrieve the network the interface is connected to

    :param iface: network interface
    :return: the network ssid or the empty string
    """

    wifi = Wireless(iface)
    ssid = wifi.getEssid()
    return ssid
예제 #21
0
    def run(self):
        self.animator.logoAnimation()
        self.animator.welcome_frame()
        wifi = Wireless('wlan0')
        while wifi.getEssid() == "":
            waiting_frame()

        self.animator.screenUpdateMode(1)
        while True:
            self.animator.testing()
            time.sleep(5)
예제 #22
0
    def getSignalLevel(self):
	wifi = Wireless('wlan1') 
	essid = wifi.getEssid()
	signal = "xx"
	try:
	  signal = wifi.getQualityAvg().signallevel
	  self.signalLevel.setValue(signal)
	except:
	  pass
	self.signalLevel.setFormat(str(essid)+"  "+str(signal))
	return True
예제 #23
0
class Wifi(Network):
    def __init__(self, interfaceName='wlan0'):
        self.interfaceName = interfaceName
        self.wifi = Wireless(interfaceName)
        super(Wifi, self).__init__()
        self.event.broadcast('wifi.connected')

    def getSSID(self):
        return self.wifi.getEssid()

    def getMode(self):
        return self.wifi.getMode()

    def getWirelessName(self):
        return self.wifi.getWirelessName()

    def getBitRate(self):
        bitrate = self.wifi.wireless_info.getBitrate()
        return "Bit Rate :%s" % self.wifi.getBitrate()

    def getAvgSignalStrength(self):
        mq = self.wifi.getQualityAvg()
        return "quality: " + str(mq.quality) + " signal: " + str(mq.siglevel) \
                + " noise: " + str(mq.nlevel)

    def getMaxSignalStrength(self):
        mq = self.wifi.getQualityMax()
        return "quality: " + str(mq.quality) + " signal: " + str(mq.siglevel) \
                + " noise: " + str(mq.nlevel)

    def disconnect(self):
        os.system("ifconfig " + self.interfaceName + " down")
        self.event.broadcast('wifi.disconnected')
        super(Wifi, self).disconnect()

    def connect(self):
        os.system("ifconfig " + self.interfaceName + " up")
        self.event.broadcast('wifi.connected')
        super(Wifi, self).connect()

    # EFFECTS: Returns the AP address.
    def getAPAddress(self):
        self.disconnect()
        time.sleep(5)
        self.connect()
        return self.wifi.getAPaddr()

    def getConnectionStatus(self):
        raise Exception('WiFi mode doesn\'t support this call yet')

    def setAPAddress(self, ap):
        try:
            self.wifi.setAPaddr(ap)
        except:
            raise Exception('Unable to set AP address to ' + str(ap))

    def isConnected(self):
        return True
예제 #24
0
파일: pycar.py 프로젝트: Afterglow/pycar
  def updateStates(self):
    try:
      wifi = Wireless('wlan0')
      ap_addr = wifi.getAPaddr()

      # Update Wifi Status
      if (ap_addr == "00:00:00:00:00:00"):
        self.ui.lblWifiStatus.setText('Not associated')
      else:
        self.ui.lblWifiStatus.setText(str(wifi.getEssid())+" connected")

      # Update 3G status
      ## Grep for route here

      # Update internet connectivity status
      response = os.system("ping -c 1 google.co.uk > /dev/null")
      if response == 0:
        self.ui.lblNetStatus.setText('Connected')
        netConnected = 1
      else:
        self.ui.lblNetStatus.setText('Not Connected')
        netConnected = 0

      # Update chef status
      response = os.system("ps auwwwx | grep -q chef-client")
      if response == 1:
        self.ui.lblChefRunStatus.setText('Running...')
      else:
        self.ui.lblChefRunStatus.setText('Not Running')
      try:
        f = open('/tmp/chef-lastrun')
        self.ui.lblChefStatus.setText(f.read())
        f.close()
      except:
        self.ui.lblChefStatus.setText('Unable to read')
      
      if netConnected:
        self.launchTimer = self.launchTimer - 1
        self.ui.btnLaunch.setEnabled(True)
      else:
        self.launchTimer = 15
        self.ui.btnLaunch.setEnabled(False)

      if self.launchTimer == 0:
        self.LoginForm = LoginForm()
        self.LoginForm.show()
        self.hide()

      self.ui.btnLaunch.setText("Launch ("+str(self.launchTimer)+")")
  
    finally:
      QtCore.QTimer.singleShot(1000, self.updateStates)
예제 #25
0
    def paintInterface(self, painter, option, rect):
        wifi=Wireless('wlan0')
        dump,qual,dump,dump=wifi.getStatistics()
        self.chart.addSample([qual.signallevel-qual.noiselevel,qual.quality,100+qual.signallevel])
	self.chart.setShowTopBar(False)
	self.chart.setShowVerticalLines(False)
	self.chart.setShowHorizontalLines(False)
	self.chart.setShowLabels(False)
	self.chart.setStackPlots(False)
	self.chart.setUseAutoRange(True)
	painter.save()
        painter.setPen(Qt.black)
        self.label.setText("ESSID: %s\nLink quality: %02d/100\nSignal level: %02ddB\nSignal/Noise: %02ddB"%(wifi.getEssid(),qual.quality,qual.signallevel,qual.signallevel-qual.noiselevel))
        painter.restore()
예제 #26
0
    def __init__(self):
        rospy.init_node('sysinfo')
        pub = rospy.Publisher('dashboard/sysinfo', SysInfo)
        pub_diagnostics = rospy.Publisher('/diagnostics', DiagnosticArray)
        rospy.Subscriber('dashboard/battery_status', BatteryStatus,
                         self.cb_base_bat)

        wifi_name = 'wlan0'
        if rospy.has_param('~wifi_name'):
            wifi_name = rospy.get_param('~wifi_name')
        self.wifi = Wireless(wifi_name)

        self.eth_name = 'eth0'
        if rospy.has_param('~eth_name'):
            self.eth_name = rospy.get_param('~eth_name')

        self.base_bat_voltage = -1
        self.base_bat_watt = -1
        self.base_bat_percent = -1
        self.base_bat_temp = -1
        self.base_bat_plugged_in = False

        #self.stat_bat_base = []
        self.stat_bat_pc = []
        self.stat_network = []
        self.stat_system = []

        info_msg = SysInfo()
        info_msg.hostname = socket.gethostname()

        diag_msg = DiagnosticArray()

        r = rospy.Rate(1)

        while not rospy.is_shutdown():
            info_msg.header.stamp = rospy.Time.now()
            info_msg.system = self.system_status()
            info_msg.network = self.network_status(self.eth_name)
            info_msg.battery_pc = self.battery_pc_status()
            info_msg.battery_base = self.battery_base_status()
            pub.publish(info_msg)

            diag_msg.header.stamp = rospy.Time.now()
            #diag_msg.status.append(self.stat_bat_base)
            diag_msg.status.append(self.stat_bat_pc)
            diag_msg.status.append(self.stat_network)
            diag_msg.status.append(self.stat_system)
            pub_diagnostics.publish(diag_msg)

            r.sleep()
예제 #27
0
파일: scan.py 프로젝트: ksami/cg3002py
class WifiNodes:
    def __init__(self, ifname):
        self.nodes = {}
        self.wifi = Wireless(ifname)

    def addNode(self, mac, lvl, id=99):
        # if it already exists
        if id in self.nodes.keys():
            if mac in self.nodes[id].keys():
                if (lvl < self.nodes[id][mac]["min"]):
                    self.nodes[id][mac]["min"] = lvl
                if (lvl > self.nodes[id][mac]["max"]):
                    self.nodes[id][mac]["max"] = lvl
            else:
                self.nodes[id][mac] = {"min": lvl, "max": lvl}
        else:
            self.nodes[id] = {mac: {"min": lvl, "max": lvl}}

    def scan(self, id=99):
        try:
            results = self.wifi.scan()
        except IOError, (error_number, error_string):
            if error_number != errno.EPERM:
                sys.stderr.write(
                    "%-8.16s  Interface doesn't support scanning : %s\n\n" %
                    (self.wifi.ifname, error_string))
        else:
예제 #28
0
파일: LeWifi.py 프로젝트: c0nn3ct/lewifi
    def OnInit(self):
        frame = MyFrame(None, -1, 'Wifi Mapper')
        frame.Show(True)
        self.SetTopWindow(frame)

        frame.wifi = Wireless(options.ifname)
        return True
예제 #29
0
class Ethernet(Network):
    def __init__(self, interfaceName='eth0'):
        self.interfaceName = interfaceName
        # TODO(zheng): change to ethernet library
        self.ethernet = Wireless(interfaceName)
        super(Ethernet, self).__init__()

    def getBitRate(self):
        bitrate = self.ethernet.wireless_info.getBitrate()
        return "Bit Rate :%s" % self.ethernet.getBitrate()

    def disconnect(self):
        os.system("ifconfig " + self.interfaceName + " down")
        self.event.broadcast('ethernet.disconnected')
        super(Ethernet, self).disconnect()

    def connect(self):
        os.system("ifconfig " + self.interfaceName + " up")
        self.event.broadcast('ethernet.connected')
        super(Ethernet, self).connect()

    def isConnected(self):
        return True

    def getConnectionStatus(self):
        raise Exception('Ethernet mode doesn\'t support this call')

    def getSignalStrength(self):
        raise Exception('Ethernet mode doesn\'t support this call')
예제 #30
0
파일: routing.py 프로젝트: avsm/signpost
 def get_intf_details(self, ip):
     rnode = self._radix.search_best(ip)
     intf = rnode.data["intf"]
     wifi = Wireless(intf)
     res = wifi.getEssid()
     if type(res) is tuple:
         dst_mac = ""
         if rnode.data["gw"] == "0.0.0.0":
             dst_mac = self._lookup_mac(ip)
         #                print "the ns %s has a mac %s"%(ip, dst_mac)
         else:
             dst_mac = self._lookup_mac(rnode.data["gw"])
         #                print "the gw %s has a mac %s"%(rnode.ata['gw'], dst_mac)
         return dict(is_wireless=False, dst_mac=dst_mac, intf=intf, essid="", ns=ip)
     else:
         return dict(is_wireless=True, dst_mac=wifi.getAPaddr(), intf=intf, essid=res, ns=ip)
예제 #31
0
	def queryWirelessDevice(self,iface):
		try:
			from pythonwifi.iwlibs import Wireless
			import errno
		except ImportError:
			return False
		else:
			try:
				ifobj = Wireless(iface) # a Wireless NIC Object
				wlanresponse = ifobj.getAPaddr()
			except IOError, (error_no, error_str):
				if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM):
					return False
				else:
					print "error: ",error_no,error_str
					return True
			else:
예제 #32
0
def main():
    # if only program name is given, print usage info
    if len(sys.argv) == 1:
        ifname = "wlan0"
    else:
        ifname = sys.argv[1]
    wifi = Wireless(ifname)
    print_probable_keys(wifi)
예제 #33
0
def get_wifi():
    if not get_ip_by_interface('wlan0'):
        return None

    try:
        wifi = Wireless('wlan0')
        aq = wifi.getQualityAvg()

        return {
            'essid': wifi.getEssid(),
            'frequency': wifi.getFrequency(),
            'quality': aq.quality,
            'signal': aq.siglevel,
            'noise': aq.nlevel
        }
    except Exception as e:
        return str(e)
예제 #34
0
def scanWifiIwlist(interface):
    try:
        logger.log("scanning on " + str(interface) + "...")
        time = datetime.now()
        wifi = Wireless(interface)
        results = wifi.scan()
        logger.log("Scan completed: %s access points found" % len(results))
        (num_channels, frequencies) = wifi.getChannelInfo()

        scan_results = {}

        for ap in results:
            ap_dict = {
                'bssid':
                ap.bssid,
                # This is rss and not rssi
                'rssi':
                ap.quality.getSignallevel(),
                'ssid':
                None if not ap.essid else ap.essid,
                'time':
                str(time),
                'frequency':
                ap.frequency.getFrequency(),
                #'channel': frequencies.index(wifi._formatFrequency(ap.frequency.getFrequency())),
                'mode':
                ap.mode,
                'quality':
                "%s/%s" % (ap.quality.quality, wifi.getQualityMax().quality),
                'noise':
                ap.quality.getNoiselevel(),
                'extra':
                ap.custom,
            }
            scan_results[ap.bssid] = ap_dict

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

    except Exception as error:
        logger.log(error)
        raise error
예제 #35
0
파일: Wlan.py 프로젝트: youcefff75/enigma2
	def getNetworkList(self):
		if self.oldInterfaceState is None:
			self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
		if self.oldInterfaceState is False:
			if iNetwork.getAdapterAttribute(self.iface, "up") is False:
				iNetwork.setAdapterAttribute(self.iface, "up", True)
				system("ifconfig "+self.iface+" up")

		ifobj = Wireless(self.iface) # a Wireless NIC Object

		try:
			scanresults = ifobj.scan()
		except:
			scanresults = None
			print "[Wlan.py] No wireless networks could be found"
		aps = {}
		if scanresults is not None:
			(num_channels, frequencies) = ifobj.getChannelInfo()
			index = 1
			for result in scanresults:
				bssid = result.bssid

				if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
					encryption = False
				elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
					encryption = True
				else:
					encryption = None

				signal = str(result.quality.siglevel-0x100) + " dBm"
				quality = "%s/%s" % (result.quality.quality,ifobj.getQualityMax().quality)

				extra = []
				for element in result.custom:
					element = element.encode()
					extra.append( strip(self.asciify(element)) )
				for element in extra:
					if 'SignalStrength' in element:
						signal = element[element.index('SignalStrength')+15:element.index(',L')]
					if 'LinkQuality' in element:
						quality = element[element.index('LinkQuality')+12:len(element)]

				# noinspection PyProtectedMember
				aps[bssid] = {
					'active' : True,
					'bssid': result.bssid,
					'channel': frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
					'encrypted': encryption,
					'essid': strip(self.asciify(result.essid)),
					'iface': self.iface,
					'maxrate' : ifobj._formatBitrate(result.rate[-1][-1]),
					'noise' : '',#result.quality.nlevel-0x100,
					'quality' : str(quality),
					'signal' : str(signal),
					'custom' : extra,
				}

				index += 1
		return aps
예제 #36
0
	def getNetworkList(self):
		system("ifconfig "+self.iface+" up")
		ifobj = Wireless(self.iface) # a Wireless NIC Object
		
		#Association mappings
		#stats, quality, discard, missed_beacon = ifobj.getStatistics()
		#snr = quality.signallevel - quality.noiselevel

		try:
			scanresults = ifobj.scan()
		except:
			scanresults = None
			print "[Wlan.py] No Wireless Networks could be found"
		
		if scanresults is not None:
			aps = {}
			(num_channels, frequencies) = ifobj.getChannelInfo()
			index = 1
			for result in scanresults:
				bssid = result.bssid

				if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
					encryption = False
				elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
					encryption = True
				else:
					encryption = None
				
				signal = str(result.quality.siglevel-0x100) + " dBm"
				quality = "%s/%s" % (result.quality.quality,ifobj.getQualityMax().quality)
				
				extra = []
				for element in result.custom:
					element = element.encode()
					extra.append( strip(self.asciify(element)) )
				for element in extra:
					print element
					if 'SignalStrength' in element:
						signal = element[element.index('SignalStrength')+15:element.index(',L')]					
					if 'LinkQuality' in element:
						quality = element[element.index('LinkQuality')+12:len(element)]				

				aps[bssid] = {
					'active' : True,
					'bssid': result.bssid,
					'channel': frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
					'encrypted': encryption,
					'essid': strip(self.asciify(result.essid)),
					'iface': self.iface,
					'maxrate' : ifobj._formatBitrate(result.rate[-1][-1]),
					'noise' : '',#result.quality.nlevel-0x100,
					'quality' : str(quality),
					'signal' : str(signal),
					'custom' : extra,
				}
				#print "GOT APS ENTRY:",aps[bssid]
				index = index + 1
			return aps
예제 #37
0
def sniff_wifi():
 if plat=='OSX':
  # bridge to objective c(apple stuff)
  objc.loadBundle('CoreWLAN',
                bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
                module_globals=globals())

  for iname in CWInterface.interfaceNames():
    interface = CWInterface.interfaceWithName_(iname)
    wifi_parameters= 'Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s, RSSI:           %s' % (iname, interface.ssid(), interface.transmitRate(), interface.transmitPower(), interface.rssi())
 elif plat=='LINUX':
  interface=Wireless('wlan1')
  stat, qual, discard, missed_beacon = interface.getStatistics()
  # Link Quality, Signal Level and Noise Level line
  wifi_parameters= 'Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s, RSSI:           %s'   % ('wlan1',   interface.getEssid(), interface.getBitrate(), interface.getTXPower(), qual.signallevel)
 
 #record wifi parameters
 print wifi_parameters
 open(channels_file, "a").write(wifi_parameters+'\n')
예제 #38
0
    def resolve_Interfaces(self):
        for data in self.ifaces:
            try:
                Wireless(data).getWirelessName()
                self.dict_type[data] = 'wireless'
            except IOError:
                self.dict_type[data] = 'non-wireless'
        for data in self.ifaces:
            try:
                info = netifaces.ifaddresses(data)[netifaces.AF_INET][0]
                self.dict_ipaddr[data] = info['addr']
                self.dict_mask[data] = info['netmask']
                if info.has_key('peer'):
                    self.dict_type[data] = 'localhost'
                    self.dict_status[data] = 'connected'
                elif self.dict_type[data] != 'wireless':
                    self.dict_type[data] = 'ethernet'
                    self.dict_status[data] = 'connected'
                else:
                    self.dict_status[data] = 'connected'
            except KeyError:
                self.dict_status[data] = 'not-connected'
                self.dict_ipaddr[data] = self.dict_mask[data] = '-'
        for data in self.ifaces:
            self.dict_ssid[data] = self.dict_mode[data] = self.dict_wname[
                data] = self.dict_apaddr[data] = '-'
            try:
                if self.dict_type[data] == 'wireless' and self.dict_status[data] == 'connected':
                    self.dict_ssid[data] = Wireless(data).getEssid()
                    self.dict_apaddr[data] = Wireless(data).getAPaddr()
                self.dict_mode[data] = Wireless(data).getMode()
                self.dict_wname[data] = Wireless(data).getWirelessName()
            except IOError:
                pass

        for data in self.dict_type:
            if self.dict_type[data] == 'wireless':
                self.ifaces_wireless.append(data)
            elif self.dict_type[data] == 'ethernet':
                self.ifaces_ethernet.append(data)
            elif self.dict_type[data] == 'localhost':
                self.ifaces_localhost.append(data)
        return True
예제 #39
0
 def run(self):
     try:
         Wireless(self.interface).setFrequency("%.3f" %
                                               (float(self.freq) / 1000))
     except IOError:
         print >> sys.stderr, traceback.format_exc()
         print >> sys.stderr, "meh"
         return
     self.hist = []
     #print >>sys.stderr, "looking for %s on %s chan: %s (%s)" % (self.mac, self.interface, chanmap[self.freq[0]+self.freq[2:5]], self.freq)
     sniff(iface=self.interface, prn=self.handler, store=0)
예제 #40
0
  def topTen(clazz):
    IOCapture.startCapture()
    networks = []

    try:
      for i in getNICnames():
        w = Wireless(i)
        networks.extend(w.scan())
    finally:
      IOCapture.stopCapture()

    
    networks.sort(lambda a,b: cmp(a.quality.quality, b.quality.quality), 
                  None, True)

    print "Networks sorted by probable proximity"

    for network in enumerate(networks):
      print '    %s) %s (%s, %s)' % (network[0], network[1].essid,
                                     network[1].quality.siglevel,
                                     network[1].quality.quality)
예제 #41
0
def get_ap_bssid(w_nic, essid):
    # Not needed if python-wifi gets fixed
    wifi = Wireless(w_nic)
    wifi.setEssid(essid)
    while wifi.getAPaddr() == '00:00:00:00:00:00)':
        time.sleep(1)
    return wifi.getAPaddr()
예제 #42
0
파일: Wlan.py 프로젝트: OUARGLA86/enigma2
    def getNetworkList(self):
        if self.oldInterfaceState is None:
            self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
        if self.oldInterfaceState is False:
            if iNetwork.getAdapterAttribute(self.iface, "up") is False:
                iNetwork.setAdapterAttribute(self.iface, "up", True)
                system("ifconfig " + self.iface + " up")

        ifobj = Wireless(self.iface)  # a Wireless NIC Object

        try:
            scanresults = ifobj.scan()
        except:
            scanresults = None
            print "[Wlan.py] No wireless networks could be found"
        aps = {}
        if scanresults is not None:
            (num_channels, frequencies) = ifobj.getChannelInfo()
            index = 1
            for result in scanresults:
                bssid = result.bssid

                if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
                    encryption = False
                elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
                    encryption = True
                else:
                    encryption = None

                signal = str(result.quality.siglevel - 0x100) + " dBm"
                quality = "%s/%s" % (result.quality.quality, ifobj.getQualityMax().quality)

                extra = []
                for element in result.custom:
                    element = element.encode()
                    extra.append(strip(self.asciify(element)))
                for element in extra:
                    if "SignalStrength" in element:
                        signal = element[element.index("SignalStrength") + 15 : element.index(",L")]
                    if "LinkQuality" in element:
                        quality = element[element.index("LinkQuality") + 12 : len(element)]

                        # noinspection PyProtectedMember
                aps[bssid] = {
                    "active": True,
                    "bssid": result.bssid,
                    "channel": frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
                    "encrypted": encryption,
                    "essid": strip(self.asciify(result.essid)),
                    "iface": self.iface,
                    "maxrate": ifobj._formatBitrate(result.rate[-1][-1]),
                    "noise": "",  # result.quality.nlevel-0x100,
                    "quality": str(quality),
                    "signal": str(signal),
                    "custom": extra,
                }

                index += 1
        return aps
예제 #43
0
파일: Wlan.py 프로젝트: dazulrich/dvbapp
	def getNetworkList(self):
		if self.oldInterfaceState is None:
			self.oldInterfaceState = iNetwork.getAdapterAttribute(self.iface, "up")
		if self.oldInterfaceState is False:
			if iNetwork.getAdapterAttribute(self.iface, "up") is False:
				iNetwork.setAdapterAttribute(self.iface, "up", True)
				enigma.eConsoleAppContainer().execute("ifconfig %s up" % self.iface)

		ifobj = Wireless(self.iface) # a Wireless NIC Object

		try:
			scanresults = ifobj.scan()
		except:
			scanresults = None
			print "[Wlan.py] No wireless networks could be found"
		aps = {}
		if scanresults is not None:
			(num_channels, frequencies) = ifobj.getChannelInfo()
			index = 1
			for result in scanresults:
				bssid = result.bssid

				if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
					encryption = False
				elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
					encryption = True
				else:
					encryption = None

				signal = str(result.quality.siglevel-0x100) + " dBm"
				quality = "%s/%s" % (result.quality.quality,ifobj.getQualityMax().quality)

				extra = []
				for element in result.custom:
					element = element.encode()
					extra.append( strip(self.asciify(element)) )
				for element in extra:
					if 'SignalStrength' in element:
						signal = element[element.index('SignalStrength')+15:element.index(',L')]
					if 'LinkQuality' in element:
						quality = element[element.index('LinkQuality')+12:len(element)]

				# noinspection PyProtectedMember
				aps[bssid] = {
					'active' : True,
					'bssid': result.bssid,
					'channel': frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
					'encrypted': encryption,
					'essid': strip(self.asciify(result.essid)),
					'iface': self.iface,
					'maxrate' : ifobj._formatBitrate(result.rate[-1][-1]),
					'noise' : '',#result.quality.nlevel-0x100,
					'quality' : str(quality),
					'signal' : str(signal),
					'custom' : extra,
				}

				index += 1
		return aps
예제 #44
0
	def ScanAp( self, aDev ) :
		from pythonwifi.iwlibs import Wireless
		import pythonwifi.flags
		status = None
		try :
			scanResult = None
			if GetCurrentNetworkType( ) != NETWORK_WIRELESS :
				os.system( 'ifup %s' % aDev )
			wifi = Wireless( aDev )

			scanResult  = wifi.scan( )
			if scanResult != None :
				apList = []
				for ap in scanResult :
					if len( ap.essid ) > 0 :
						apInfoList = []
						apInfoList.append( ap.essid )
						apInfoList.append( ap.quality.getSignallevel( ) )
						if ap.encode.flags & pythonwifi.flags.IW_ENCODE_DISABLED :
							apInfoList.append( 'No' )
						else :
							apInfoList.append( 'Yes' )
						apList.append( apInfoList )
				if apList :
					status = apList 
				else :
					status = None

			if GetCurrentNetworkType( ) != NETWORK_WIRELESS :
				os.system( 'ifdown %s' % aDev )
			return status

		except Exception, e :
			LOG_ERR( 'Error exception[%s]' % e )
			if GetCurrentNetworkType( ) != NETWORK_WIRELESS :
				os.system( 'ifdown %s' % aDev )
			status = None
			return status
예제 #45
0
파일: Wlan.py 프로젝트: FFTEAM/enigma2-5
	def getNetworkList(self):
		system("ifconfig "+self.iface+" up")
		ifobj = Wireless(self.iface) # a Wireless NIC Object
		
		#Association mappings
		#stats, quality, discard, missed_beacon = ifobj.getStatistics()
		#snr = quality.signallevel - quality.noiselevel

		try:
			scanresults = ifobj.scan()
		except:
			scanresults = None
			print "[Wlan.py] No Wireless Networks could be found"
		
		if scanresults is not None:
			aps = {}
			(num_channels, frequencies) = ifobj.getChannelInfo()
			index = 1
			for result in scanresults:
				bssid = result.bssid

				if result.encode.flags & wififlags.IW_ENCODE_DISABLED > 0:
					encryption = False
				elif result.encode.flags & wififlags.IW_ENCODE_NOKEY > 0:
					encryption = True
				else:
					encryption = None
				
				signal = str(result.quality.siglevel-0x100) + " dBm"
				quality = "%s/%s" % (result.quality.quality,ifobj.getQualityMax().quality)
				
				extra = []
				for element in result.custom:
					element = element.encode()
					extra.append( strip(self.asciify(element)) )
				for element in extra:
					print element
					if 'SignalStrength' in element:
						signal = element[element.index('SignalStrength')+15:element.index(',L')]					
					if 'LinkQuality' in element:
						quality = element[element.index('LinkQuality')+12:len(element)]				

				aps[bssid] = {
					'active' : True,
					'bssid': result.bssid,
					'channel': frequencies.index(ifobj._formatFrequency(result.frequency.getFrequency())) + 1,
					'encrypted': encryption,
					'essid': strip(self.asciify(result.essid)),
					'iface': self.iface,
					'maxrate' : ifobj._formatBitrate(result.rate[-1][-1]),
					'noise' : '',#result.quality.nlevel-0x100,
					'quality' : str(quality),
					'signal' : str(signal),
					'custom' : extra,
				}
				#print "GOT APS ENTRY:",aps[bssid]
				index = index + 1
			return aps
예제 #46
0
def getWiFiList():
    ifdata = Ifcfg(commands.getoutput('ifconfig -a'))
    wifiList = []
    for interface in ifdata.interfaces:
        try:
            wifi = Wireless(interface)
            essid = wifi.getEssid()
            cmd = subprocess.Popen('iwconfig %s' % interface,
                                   shell=True,
                                   stdout=subprocess.PIPE)
            for line in cmd.stdout:
                if 'Link Quality' in line:
                    sigIndex = line.find("Signal level")
                    levelStr = line[sigIndex + 13:]
                    value = 0
                    dBm_value = 0
                    percent = 0
                    if 'dBm' in levelStr:
                        value = int(levelStr.split(" ")[0])
                        dBm_value = value
                        # -35 dBm < signal 100%
                        # -95 dBm > signal 0%
                        if dBm_value > -35:
                            percent = 100
                        elif dBm_value < -95:
                            percent = 0
                        else:
                            percent = (value + 95) * 100 / 60
                            pass
                    if '/' in levelStr:
                        value = int(levelStr.split("/")[0])
                        percent = value
                        dBm_value = (value * 60 / 100) - 95
                    wifiDescriptor = [interface, essid, dBm_value, percent]
                    wifiList.append(wifiDescriptor)
        except IOError:
            pass
    return wifiList
예제 #47
0
    def run(self):
        """
        run the plugin
        """
        current_targets = set()
        logging.debug(str(self.__class__) + " Scanning for wlan devices")
        
        try:
            wifi = Wireless( self._pcc.get_cfg("wlan_device") )
            results = wifi.scan()
        except IOError:
            raise PermissionDenied("Cannot scan for wifi :(")
            sys.exit(1)
        
        if len(results) > 0:
            for ap in results:
#               print ap.bssid + " " + frequencies.index(wifi._formatFrequency(ap.frequency.getFrequency())) + " " + ap.essid + " " + ap.quality.getSignallevel()
                target = airxploit.core.target.Wlan()
                target.quality = ap.quality.getSignallevel()
                target.name = ap.essid
                target.addr = ap.bssid
                target.channel = WlanScanner.frequency_channel_map.get( ap.frequency.getFrequency() )
                current_targets.add(target)
                logging.debug(str(self.__class__) + " Found wlan device " + ap.bssid + " " + " " + ap.essid)

        if self.result == current_targets:
            got_new_targets = False
        else:
            got_new_targets = True

        if got_new_targets:
            for target in current_targets:
                if target not in self.result:
                    self._pcc.add_target( target )

            self.result = current_targets
            self._pcc.fire_event(WlanScanner.EVENT)    
예제 #48
0
class ChipWifi:
  def __init__(self):
      self.clients = dict()
      w = Wireless("wlan0")
      ap = w.getAPaddr()
      self.AP = ap.lower()
      self.freq=w.getFrequency()
      self.ifname = "wlan1"
      os.system("/sbin/ifconfig %s down" % (self.ifname))
      self.wifi = Wireless(self.ifname)
      self.oldmode = self.wifi.getMode()
      self.wifi.setMode("monitor")
      os.system("/sbin/ifconfig %s up" % (self.ifname)) 
      self.wifi.setFrequency(self.freq)
  def __del__(self):
      os.system("/sbin/ifconfig %s down" % (self.ifname))
      self.wifi.setMode(self.oldmode)
  def run(self):
      sniff(iface=self.ifname,prn=self.packet,store = 0)
  def probe(self,client):
      if client in self.clients.keys():
         self.clients[client].mon()
  def presponse(self,server,client):
      if client in self.clients.keys():
          if server == self.AP:
              self.clients[client].home()
          else:
              self.clients[client].other(server)
  def activeclient(self,client):
      if not client in self.clients.keys():
          self.clients[client]=Client(client)
      self.clients[client].home()
  def packet(self,p):
      if p.haslayer(Dot11ProbeReq):
          if p[Dot11].addr2 in self.clients:
              self.probe(p[Dot11].addr2)
      else:
          if p.haslayer(Dot11ProbeResp):
              self.presponse(p[Dot11].addr2,p[Dot11].addr1)
          else: 
              if p[Dot11].addr1 == self.AP and p[Dot11].addr2 != None and p[Dot11].type == 2:
                  self.activeclient(p[Dot11].addr2)
  def tick(self):
      for mac in self.clients.keys():
          self.clients[mac].tick()
      data = list()
      for mac in self.clients.keys():
          data.append(self.clients[mac].asobj())
      content = json.dumps(data,indent=4, separators=(',', ': '))
      with open('elvisscan.json', 'w') as f:
          f.write(content)
예제 #49
0
파일: routing.py 프로젝트: vermuz/signpost
    def get_intf_details(self, ip):
        rnode = self._radix.search_best(ip)
        intf = rnode.data['intf']
        wifi = Wireless(intf)
        res = wifi.getEssid()
        if (type(res) is tuple):
            dst_mac = ""
            if (rnode.data['gw'] == "0.0.0.0"):
                dst_mac = self._lookup_mac(ip)
#                print "the ns %s has a mac %s"%(ip, dst_mac)
            else:
                dst_mac = self._lookup_mac(rnode.data['gw'])
#                print "the gw %s has a mac %s"%(rnode.ata['gw'], dst_mac)
            return dict(is_wireless=False,
                        dst_mac=dst_mac,
                        intf=intf,
                        essid="",
                        ns=ip)
        else:
            return dict(is_wireless=True,
                        dst_mac=wifi.getAPaddr(),
                        intf=intf,
                        essid=res,
                        ns=ip)
예제 #50
0
def monitor_manage(cmd, iface_name):
    os.system('ifconfig {} down'.format(iface_name))
    wifi_card = Wireless(iface_name)
    if cmd == 'start':
        print('Initializing monitor mode')
        wifi_card.setMode('monitor')
    elif cmd == 'stop':
        wifi_card.setMode('managed')
    else:
        print('Unknown command. Use start or stop')
    os.system('ifconfig {} up'.format(iface_name))
예제 #51
0
파일: Wlan.py 프로젝트: FFTEAM/enigma2-5
	def getStatus(self):
		ifobj = Wireless(self.iface)
		fq = Iwfreq()
		try:
			self.channel = str(fq.getChannel(str(ifobj.getFrequency()[0:-3])))
		except:
			self.channel = 0
		status = {
				  'BSSID': str(ifobj.getAPaddr()), #ifobj.getStatistics()
				  'ESSID': str(ifobj.getEssid()),
				  'quality': "%s/%s" % (ifobj.getStatistics()[1].quality,ifobj.getQualityMax().quality),
				  'signal': str(ifobj.getStatistics()[1].siglevel-0x100) + " dBm",
				  'bitrate': str(ifobj.getBitrate()),
				  'channel': str(self.channel),
				  #'channel': str(fq.getChannel(str(ifobj.getFrequency()[0:-3]))),
		}
		
		for (key, item) in status.items():
			if item is "None" or item is "":
					status[key] = _("N/A")
				
		return status
예제 #52
0
class TestWireless(unittest.TestCase):

    def setUp(self):
        ifnames = getNICnames()
        self.wifi = Wireless(ifnames[0])

    def test_wirelessMethods(self):
        # test all wireless methods that they don't return an error
        methods = ['getAPaddr',
                   'getBitrate',
                   'getBitrates',
                   'getChannelInfo',
                   'getEssid',
                   'getFragmentation',
                   'getFrequency',
                   'getMode',
                   'getNwids',
                   'getWirelessName',
                   'getPowermanagement',
                   'getQualityMax',
                   'getQualityAvg',
                   'getRetrylimit',
                   'getRTS',
                   'getSensitivity',
                   'getTXPower',
                   'getStatistics',
                   'commit']

        for m in methods:
            result = getattr(self.wifi, m)()

        old_mode = self.wifi.getMode()
        self.wifi.setMode('Monitor')
        self.assert_(self.wifi.getMode() == 'Monitor')
        self.wifi.setMode(old_mode)

        old_essid = self.wifi.getEssid()
        self.wifi.setEssid('Joost')
        self.assert_(self.wifi.getEssid() == 'Joost')
        self.wifi.setEssid(old_essid)

        old_freq = self.wifi.getFrequency()
        self.wifi.setFrequency('2.462GHz')
        self.assert_(self.wifi.getFrequency() == '2.462GHz')
        self.wifi.setFrequency(old_freq)

        # test setAPaddr - does not work unless AP is real and available
        #old_mac = self.wifi.getAPaddr()
        #self.wifi.setAPaddr('61:62:63:64:65:66')
        #time.sleep(3)                                     # 3 second delay between set and get required
        #self.assert_(self.wifi.getAPaddr() == '61:62:63:64:65:66')
        #self.wifi.setAPaddr(old_mac)

        old_enc = self.wifi.getEncryption()
        self.wifi.setEncryption('restricted')
        self.assert_(self.wifi.getEncryption() == 'restricted')
        self.assert_(self.wifi.getEncryption(symbolic=False) \
                        == IW_ENCODE_RESTRICTED+1)
        self.wifi.setEncryption(old_enc)

        try:
            old_key = self.wifi.getKey()
        except ValueError, msg:
            old_key = None
        self.wifi.setKey('ABCDEF1234', 1)
        self.assert_(self.wifi.getKey() == 'ABCD-EF12-34')
        self.assert_(map(hex, self.wifi.getKey(formatted=False)) \
                        == ['0xab', '0xcd', '0xef', '0x12', '0x34'])
        if old_key:
            self.wifi.setKey(old_key, 1)
        else:
            self.wifi.setEncryption('off')
예제 #53
0
파일: wlan-scanner.py 프로젝트: Cergoo/junk
    5320000000: "64",
    5500000000: "100",
    5520000000: "104",
    5540000000: "108",
    5560000000: "112",
    5580000000: "116",
    5600000000: "120",
    5620000000: "124",
    5640000000: "128",
    5660000000: "132",
    5680000000: "136",
    5700000000: "140",
    5735000000: "147",
    5755000000: "151",
    5775000000: "155",
    5795000000: "159",
    5815000000: "163",
    5835000000: "167",
    5785000000: "171"
}

wifi = Wireless("wlan0")

for ap in wifi.scan():
    print "SSID: " + ap.essid
    print "AP: " + ap.bssid
    print "Signal: " + str(ap.quality.getSignallevel())
    print "Frequency: " + str(ap.frequency.getFrequency())
    print "Channel: " + frequency_channel_map.get(ap.frequency.getFrequency())
    print ""
예제 #54
0
 def getSSID():
   wifi = Wireless('wlan0')
   return wifi.getEssid()
예제 #55
0
def main():
    global ip_lst
    # status.noc.stonybrook.edu
    parser = argparse.ArgumentParser(description="man on the side attack detector.")
    parser.add_argument("-i", "--ifname", help="interface to use", type=str, required=False, default="wlp1s0")

    parser.add_argument("-o", "--out-file", help="file to write live ip's to", type=str, required=False, default=None)

    parser.add_argument(
        "-t",
        "--cache-clear-interv",
        help="how long to wait before clearing the ARP cache",
        type=int,
        required=False,
        default=0,
    )

    parser.add_argument(
        "-m", "--mu", help="how long to wait before pinging the next random IP", type=float, required=False, default=0
    )

    args = parser.parse_args()

    ifname = args.ifname

    mask = get_netmask(ifname)
    ip_str = get_ipaddress(ifname)

    print("mask: " + mask)
    print("ip: " + ip_str)

    ip = netaddr.IPNetwork(ip_str + "/" + mask)
    print(ip)

    found_ips = []

    # scan whole network for live computers
    ans, unans = arping(str(ip.network) + "/" + str(ip.prefixlen), iface=ifname)

    # record all of the live IP's
    for i in ans:
        found_ips.append(i[0][ARP].pdst)

    print("found " + str(len(found_ips)) + " IPs")

    # write the IP's to a file if requested
    if args.out_file is not None:
        outfile = open(args.out_file, "w")
        wifi = Wireless(ifname)
        outfile.write("args: " + str(args) + "\n")
        outfile.write("essid: " + wifi.getEssid() + "\n")
        outfile.write("mode: " + wifi.getMode() + "\n")
        outfile.write("mask: " + mask + "\n")
        outfile.write("ip: " + ip_str + "\n")
        outfile.write("network: " + str(ip.network) + "/" + str(ip.prefixlen) + "\n")

        outfile.write("\n".join(found_ips))
        outfile.write("\n")
        outfile.close()

    # schedule the ARP cache clearing
    if args.cache_clear_interv > 0:
        t = threading.Thread(target=clear_cache_timer, args=[args.cache_clear_interv])
        t.start()

    # schedule the pinging
    if args.mu <= 0:
        sys.exit(1)

    ip_lst = found_ips
    random.shuffle(ip_lst)

    # signal.signal(signal.SIGALRM, ping_rnd)
    # signal.setitimer(signal.ITIMER_REAL, args.mu, args.mu)

    while True:
        # signal.pause()
        t = threading.Thread(target=ping_rnd, args=["", ""])
        t.start()
        time.sleep(args.mu)
예제 #56
0
 def __init__(self, wireless, x=0, y=0):
     self.w=Wireless(wireless)
     self.rm=None
     self.x=x
     self.y=y
     self.aps={}
예제 #57
0
 def setUp(self):
     ifnames = getNICnames()
     self.wifi = Wireless(ifnames[0])
예제 #58
0
parser = OptionParser(usage = use)

parser.add_option("-v", "--verbose", 
  dest="verbose", action="store_true", default=False, help="Verbose output.")

options, args = parser.parse_args()

if len(args) != 1:
   parser.print_usage()
   exit(1)

interface = args[0]


# Get a handle to the card
wifi = Wireless(interface)

current_essid = None
current_ap_addr = None
SAMPLE_WINDOW_SIZE = 10
SIGMA_MUL = 5
SIGMA_MIN = 2
SAMPLE_FREQ_HZ = 2

if options.verbose:
    print("Scanning for rouge AP's. Ctrl-C to exit.")

# Start processing. Ctrl-C to exit
while True: 
    
    time.sleep(1 / SAMPLE_FREQ_HZ)
예제 #59
0
from pythonwifi.iwlibs import Wireless
wifi = Wireless('wlan0')
print wifi.getEssid()
print wifi.getMode()

예제 #60
0
class Scanner():
    def __init__(self, wireless, x=0, y=0):
        self.w=Wireless(wireless)
        self.rm=None
        self.x=x
        self.y=y
        self.aps={}

    def init_launcher(self):
        self.rm=RocketManager()
        self.rm.acquire_devices()

    def step(self,dir,steps=1, sane=False):
        if not self.rm: self.init_launcher()
        c=0
        while c<steps:
            if dir==RIGHT:
                if sane or self.x>0: self.x-=1
                else: break
            elif dir==LEFT:
                if sane or self.x<HMAX: self.x+=1
                else: break
            elif dir==UP:
                if sane or self.y<VMAX: self.y+=1
                else: break
            elif dir==DOWN:
                if sane or self.y>0: self.y-=1
                else: break
            self.rm.launchers[0].start_movement(dir)
            self.rm.launchers[0].stop_movement()
            c+=1
        if c==steps:
            return True

    def home(self):
        if not self.rm: self.init_launcher()
        print "press c-c when in home position"
        while True:
            print s.x
            try:
                s.step(RIGHT,steps=200, sane=True)
            except KeyboardInterrupt:
                self.rm.launchers[0].stop_movement()
                sys.exit(0)

    def scan(self,c=1, cb=None):
        res=[]
        for _ in xrange(c):
            tmp=[]
            for h in self.w.scan():
                try:
                    name=h.essid.decode('utf8')
                except:
                    name=h.bssid
                # TODO add
                # "Quality: Quality ", self.quality.quality
                # "Signal ", self.quality.getSignallevel()
                # "Noise ", self.quality.getNoiselevel()
                # "Encryption:", map(lambda x: hex(ord(x)), self.encode)
                # "Frequency:", self.frequency.getFrequency(), "(Channel", self.frequency.getChannel(self.range), ")"
                record=(self.x,
                        self.y,
                        datetime.now().isoformat(),
                        h.bssid,
                        h.quality.getSignallevel(),
                        name.strip())
                tmp.append(record)
            if cb: tmp=cb(tmp)
            res.extend(tmp)

        # handle callback
        for ap in res:
            # print all scan records
            print u' '.join([unicode(f) for f in ap])
            # remember all entries for later
            self.store(*ap)

        return res

    def store(self, x, y, date, bssid, rssi, name):
        try:
            self.aps[bssid]['rssi'].append((date, int(rssi), int(x), int(y)))
        except:
            self.aps[bssid]={'name': name.strip(),
                             'rssi': [(date, int(rssi), int(x), int(y))]}

    def fasth(self, c=1, steps=10, cb=None, sweeps=1):
        res=[]
        dirs=[LEFT, RIGHT]
        for i in xrange(sweeps):
            while True:
                aps=self.scan(c)
                if cb: aps=cb(aps)
                res.extend(aps)
                if not self.step(dirs[i%2],steps):
                    break
            if self.y==0:
                self.movetoy(VMAX)
            else:
                self.movetoy(0)
        return res

    def apRSSI(self, target, batch):
        # x, y, date, bssid, rssi, name
        data=[item[4] for item in batch if item[3]==target and int(item[4])>-100]
        if data:
            rssi=sum(data)/float(len(data))
            print >>sys.stderr, "%4s %4s %3.2f |%s" % (self.x, self.y, rssi, '▬'*int(rssi+100))
        else:
            print >>sys.stderr, "%4s %4s        |" % (self.x, self.y)
        return batch

    def apCount(self, batch):
        # x, y, date, bssid, rssi, name
        count=len(set([item[3] for item in batch]))
        print >>sys.stderr, "%4s %4s %s %s" % (self.x, self.y, count, '▬'*count)
        return batch

    def stats(self):
        # do some stats on the seen APs
        stats=sorted([(sum([int(rssi) for _, rssi, _, _ in v['rssi'] if rssi!='-256'])/len(v['rssi']),
                       max([int(rssi) for _, rssi, _, _ in v['rssi'] if rssi!='-256']),
                       min([int(rssi) for _, rssi, _, _ in v['rssi'] if rssi!='-256']),
                       max([int(rssi) for _, rssi, _, _ in v['rssi'] if rssi!='-256'])-min([int(rssi) for _, rssi, _, _ in v['rssi'] if rssi!='-256']),
                       key,
                       v['name'])
                      for key, v in self.aps.items()],
                     reverse=True)
        print >>sys.stderr, "avg mx mn sprd key name"
        for avg, mx, mn, sprd, key, name in stats:
            print >>sys.stderr, key, avg, mx, mn, sprd, self.aps[key]['name']

        for ap in s.ordered(by='dir'):
            print "|%s| %4s %3s %s %s %s %s" % (self.apspark(s.aps[ap[0]]), ap[4], ap[5], ap[2][:19], ap[0], ap[3], ap[1])

    def apspark(self, ap):
        radar=[[0,0] for _ in xrange(20)]
        for item in sorted(ap['rssi'],key=itemgetter(2)):
            radar[int(item[2]/((HMAX+1.0)/20))][0]+=item[1]
            radar[int(item[2]/((HMAX+1.0)/20))][1]+=1
        tmp=[x[0]/x[1] if x[1] else None for x in radar]
        if not [x for x in tmp if x]:
            return "%s" % ' '*20
        tmp=[y or min([x for x in tmp if x])-((max([x for x in tmp if x])-min([x for x in tmp if x]))/8)-1 for y in tmp]
        return "%s" % s.spark(tmp).encode('utf8')

    def load(self,file):
        for line in file.readlines():
            try:
                self.store(*line.split(' ',5))
            except TypeError:
                pass

    def ordered(self, by='dir'):
        if by=='rssi': sortby=3
        else: sortby=4
        return sorted([(ap, data['name'])+max(data['rssi'], key=itemgetter(1))
                       for ap, data in self.aps.items()],
                      key=itemgetter(sortby))

    def spark(self, data):
        lo = float(min(data))
        hi = float(max(data))
        incr = (hi - lo)/(len(blocks)-1) or 1
        return ''.join([(blocks[int((float(n) - lo)/incr)]
                        if n else
                        ' ')
                       for n in data])

    def movetox(self,x):
        dir=LEFT if self.x <= x else RIGHT
        dist=self.x - x if x <= self.x else x - self.x
        self.step(dir,dist)

    def movetoy(self,y):
        dir=UP if self.y <= y else DOWN
        dist=self.y - y if y <= self.y else y - self.y
        self.step(dir,dist)

    def randomdir(self, plane, dir):
        oplane=plane
        odir=dir
        # choose another direction
        while dir==odir and plane==oplane:
            plane=random.randint(0,2)%2
            dir=random.randint(0,1)
        return (plane, dir)

    def lock(self, target):
        # use with - where the param to tail controls how many past scans to consider:
        # cat $(ls -rt logs/*.log | tail -5) | ./wscan.py lock <bssid> >logs/$(date '+%s').log
        top=sorted(self.aps[target]['rssi'], key=itemgetter(1), reverse=True)
        sample_size=30 if len(top)>30 else len(top)
        posx=sum([x[2] for x in top][:sample_size])/sample_size
        posy=sum([x[3] for x in top][:sample_size])/sample_size
        rssi=sum([x[1] for x in top][:sample_size])/sample_size
        # go to last known best position
        print >>sys.stderr, "|%s| %4s %4s %4s" % (self.apspark(self.aps[target]), posx, posy, rssi)
        self.movetox(posx)
        self.movetoy(posy)

        prev=None
        dirs=[[LEFT,RIGHT],[UP,DOWN]]
        plane, dir=self.randomdir(None,None)
        steps=97
        lost=0
        best=None

        try:
            while True:
                # scan a bit
                pop=15

                #samples=[x[4] for x in self.scan(c=pop, cb=partial(self.apRSSI,target)) if x[3]==target]
                samples=self.scan(c=pop)
                self.apRSSI(target, samples)
                # only our own samples
                samples=[x[4] for x in samples if x[3]==target]

                # avg rssi in this direction
                # avg is fixed with missing readings, using -100db
                rssi=(sum(samples)+(-100*(pop-len(samples))))/float(pop)

                if not rssi:
                    if lost>5: break
                    lost+=1
                    if lost==3 and best:
                        # retry from last best position
                        self.movetox(best[1])
                        self.movetoy(best[2])
                        plane,dir=self.randomdir(plane,dir)
                else:
                    lost=0
                # FIXME: more efficient search algo than below

                if best and (int(best[0])-3)>int(rssi):
                    # signal degraded, backtrack
                    # retry from last best position
                    self.movetox(best[1])
                    self.movetoy(best[2])
                    plane,dir=self.randomdir(plane,dir)
                    continue

                if not best or best[0]<rssi:
                    best=(rssi, self.x, self.y)

                if (prev and int(prev)-2>int(rssi)):
                    # signal degraded
                    self.step(dirs[plane][(dir+1)%2], steps/((plane*4)+1))
                    plane,dir=self.randomdir(plane,dir)
                    continue
                prev=rssi

                # wander mindlessly
                if not self.step(dirs[plane][dir], steps/((plane*4)+1)):
                    # we hit some boundary, let's rebound
                    plane,dir=self.randomdir(plane,dir)

        except KeyboardInterrupt:
            pass
        # go home
        self.movetoy(0)
        self.movetox(0)