コード例 #1
0
ファイル: iwlist.py プロジェクト: Opvolger/pythonwifi
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, ))
コード例 #2
0
 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)
コード例 #3
0
    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
コード例 #4
0
def show_entries():
    """
    show wifi entries
    """
    wifi = Wireless('wlan0')
    essid = wifi.getEssid()
    return render_template('home.html', message=essid)
コード例 #5
0
ファイル: blackshrike.py プロジェクト: nullmuse/blackshrike
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()
コード例 #6
0
ファイル: Clocking.py プロジェクト: HviorForgeFlow/ras
    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")
コード例 #7
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
コード例 #8
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
コード例 #9
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
コード例 #10
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)
コード例 #11
0
ファイル: blackshrike.py プロジェクト: nullmuse/blackshrike
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
コード例 #12
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
コード例 #13
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
コード例 #14
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
コード例 #15
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
コード例 #16
0
ファイル: blackshrike.py プロジェクト: nullmuse/blackshrike
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')
コード例 #17
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
コード例 #18
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 ""
コード例 #19
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
コード例 #20
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)
コード例 #21
0
ファイル: mrssi.py プロジェクト: StarHeart23/SwarmRobotics
 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)
コード例 #22
0
ファイル: blackshrike.py プロジェクト: nullmuse/blackshrike
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))
コード例 #23
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__)
コード例 #24
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()
コード例 #25
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)
コード例 #26
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
コード例 #27
0
ファイル: wprox.py プロジェクト: vickxxx/wireless-radar
    def run(self, freq = None, timeout = None):
        self.end_sniffing = False
        if freq:
            self.freq = freq
        if timeout:
            self.timeout = timeout

        if self.timeout:
            self.lastseen = time.time()
        try:
            Wireless(self.interface).setFrequency(self.freq)
        except IOError:
            print >>sys.stderr, traceback.format_exc()
            print >>sys.stderr, "meh"
            return
        if self.verbose:
            self.lastshown = time.time()
            print >>sys.stderr, "listening on %s chan: %s (%s)" % (self.interface, chanmap[self.freq[0]+self.freq[2:5]], self.freq)
        while self.lastseen and self.timeout and self.lastseen+self.timeout>time.time() and not self.end_sniffing:
            sniff(iface=self.interface, prn=self.handler, timeout=self.timeout, store=0, stop_filter=self.stop_sniffing)
        return self.peers
コード例 #28
0
ファイル: wifi.py プロジェクト: husarion/husarion_ros
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
コード例 #29
0
ファイル: iwconfig.py プロジェクト: reikkaps/python3-wifi
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hv", ["help", "version"])
    except getopt.GetoptError as error:
        # invalid options will be taken to be interface name
        print(error)
    else:
        try:
            if opts[0][0] in ("-h", "--help"):
                usage()
        except:
            try:
                if opts[0][0] in ("-v", "--version"):
                    version_info()
            except:
                if len(args) == 0:
                    # no params given to iwconfig.py
                    for interface in getNICnames():
                        iwconfig(interface)
                elif len(args) == 1:
                    # one param given to iwconfig.py, it should be a network device
                    if sys.argv[1] in getNICnames():
                        iwconfig(sys.argv[1])
                else:
                    # more than one param, must be a command
                    # 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:3]
                        # look for matching command
                        set_command = get_matching_command(option)
                        # if the second argument is a command
                        if set_command is not None:
                            wifi = Wireless(ifname)
                            set_command(wifi, sys.argv[3])
                        else:
                            print "iwconfig.py: unknown command `%s' " \
                                "(check 'iwconfig.py --help')." % (option, )
コード例 #30
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)