iwconfig.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 # Copyright 2004, 2005 R�man Joost <roman@bromeco.de> - Rotterdam, Netherlands
00004 # Copyright 2009 by Sean Robinson <seankrobinson@gmail.com>
00005 #
00006 # This file is part of Python WiFi
00007 #
00008 #   This program is free software; you can redistribute it and/or modify
00009 #   it under the terms of the GNU General Public License as published by
00010 #   the Free Software Foundation; either version 2 of the License, or
00011 #   (at your option) any later version.
00012 #
00013 #   This program is distributed in the hope that it will be useful,
00014 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
00015 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016 #   GNU General Public License for more details.
00017 #
00018 #   You should have received a copy of the GNU General Public License
00019 #   along with this program; if not, write to the Free Software
00020 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00021 #
00022 import getopt
00023 import sys
00024 import types
00025 
00026 import rocon_python_wifi.flags
00027 from rocon_python_wifi.iwlibs import Wireless, WirelessInfo, Iwrange, getNICnames, getWNICnames
00028 
00029 def getBitrate(wifi):
00030     """ Return formatted string with Bit Rate info. """
00031     try:
00032         bitrate = wifi.wireless_info.getBitrate()
00033     except IOError, (errno, strerror):
00034         return None
00035     else:
00036         if bitrate.fixed:
00037             fixed = "="
00038         else:
00039             fixed = ":"
00040         return "Bit Rate%c%s   " % (fixed, wifi.getBitrate())
00041 
00042 def getTXPower(wifi):
00043     """ Return formatted string with TXPower info. """
00044     try:
00045         txpower = wifi.wireless_info.getTXPower()
00046     except IOError, (errno, strerror):
00047         return None
00048     else:
00049         if txpower.fixed:
00050             fixed = "="
00051         else:
00052             fixed = ":"
00053         return "Tx-Power%c%s   " % (fixed, wifi.getTXPower())
00054 
00055 def getSensitivity(wifi):
00056     """ Return formatted string with Sensitivity info. """
00057     try:
00058         sensitivity = wifi.wireless_info.getSensitivity()
00059     except IOError, (errno, strerror):
00060         return None
00061     else:
00062         if sensitivity.fixed:
00063             fixed = "="
00064         else:
00065             fixed = ":"
00066         iwrange = Iwrange(wifi.ifname)
00067         return "Sensitivity%c%d/%d  " % (
00068             fixed, wifi.getSensitivity(), iwrange.sensitivity)
00069 
00070 def getRetrylimit(wifi):
00071     """ Return formatted string with Retry info. """
00072     try:
00073         retry = wifi.wireless_info.getRetry()
00074     except IOError, (errno, strerror):
00075         return None
00076     else:
00077         modifier = ""
00078         if (retry.flags & pythonwifi.flags.IW_RETRY_MIN):
00079             modifier = " min"
00080         elif (retry.flags & pythonwifi.flags.IW_RETRY_MAX):
00081             modifier = " max"
00082         elif (retry.flags & pythonwifi.flags.IW_RETRY_SHORT):
00083             modifier = " short"
00084         elif (retry.flags & pythonwifi.flags.IW_RETRY_LONG):
00085             modifier = "  long"
00086         type = " limit"
00087         if (retry.flags & pythonwifi.flags.IW_RETRY_LIFETIME):
00088             type = " lifetime"
00089         return "Retry%s%s:%s   " % (modifier, type, wifi.getRetrylimit())
00090 
00091 def getRTS(wifi):
00092     """ Return formatted string with RTS info. """
00093     try:
00094         rts = wifi.wireless_info.getRTS()
00095     except IOError, (errno, strerror):
00096         return None
00097     else:
00098         if rts.disabled:
00099             return "RTS thr:off   "
00100         if rts.fixed:
00101             fixed = "="
00102         else:
00103             fixed = ":"
00104         return "RTS thr%c%d B   " % (fixed, wifi.getRTS())
00105 
00106 def getFragmentation(wifi):
00107     """ Return formatted string with Fragmentation info. """
00108     try:
00109         frag = wifi.wireless_info.getFragmentation()
00110     except IOError, (errno, strerror):
00111         return None
00112     else:
00113         if frag.disabled:
00114             return "Fragment thr:off"
00115         if frag.fixed:
00116             fixed = "="
00117         else:
00118             fixed = ":"
00119         return "Fragment thr%c%d B   " % (fixed, wifi.getFragmentation())
00120 
00121 def getEncryption(wifi):
00122     """ Return formatted string with Encryption info.
00123 
00124         As noted in iwconfig.c: we display only the "current" key, use iwlist
00125         to list all keys.
00126 
00127     """
00128     #try:
00129     enc = wifi.wireless_info.getEncryption()
00130     #except IOError, (errno, strerror):
00131         #print errno, strerror
00132         #return None
00133     #else:
00134     if (enc.flags & pythonwifi.flags.IW_ENCODE_DISABLED):
00135         key = "Encryption key:off"
00136     else:
00137         key = "Encryption key:%s" % (wifi.getKey(), )
00138     if ((enc.flags & pythonwifi.flags.IW_ENCODE_INDEX) > 1):
00139         index = " [%d]" % (enc.flags & pythonwifi.flags.IW_ENCODE_INDEX, )
00140     else:
00141         index = ""
00142     if ((enc.flags & pythonwifi.flags.IW_ENCODE_RESTRICTED) > 0):
00143         mode = "   Security mode:restricted"
00144     elif ((enc.flags & pythonwifi.flags.IW_ENCODE_OPEN) > 0):
00145         mode = "   Security mode:open"
00146     else:
00147         mode = ""
00148     return "%s%s%s" % (key, index, mode)
00149 
00150 def getPowerManagement(wifi):
00151     """ Return formatted string with Power Management info. """
00152     power = wifi.wireless_info.getPower()
00153     status = ""
00154     if (power.disabled):
00155         status = ":off"
00156     else:
00157         if (power.flags & pythonwifi.flags.IW_POWER_TYPE):
00158             if (power.flags & pythonwifi.flags.IW_POWER_MIN):
00159                 status = status + " min"
00160             if (power.flags & pythonwifi.flags.IW_POWER_MAX):
00161                 status = status + " max"
00162             if (power.flags & pythonwifi.flags.IW_POWER_TIMEOUT):
00163                 status = status + " timeout:"
00164             else:
00165                 if (power.flags & pythonwifi.flags.IW_POWER_SAVING):
00166                     status = status + " saving:"
00167                 else:
00168                     status = status + " period:"
00169         pm_mode_mask = power.flags & pythonwifi.flags.IW_POWER_MODE
00170         if (pm_mode_mask == pythonwifi.flags.IW_POWER_UNICAST_R):
00171             status = status + "mode:Receive Unicast only received"
00172         elif (pm_mode_mask == pythonwifi.flags.IW_POWER_MULTICAST_R):
00173             status = status + "mode:Receive Multicast only received"
00174         elif (pm_mode_mask == pythonwifi.flags.IW_POWER_ALL_R):
00175             status = status + "mode:All packets received"
00176         elif (pm_mode_mask == pythonwifi.flags.IW_POWER_FORCE_S):
00177             status = status + "mode:Force sending"
00178         elif (pm_mode_mask == pythonwifi.flags.IW_POWER_REPEATER):
00179             status = status + "mode:Repeat multicasts"
00180         if (power.flags & pythonwifi.flags.IW_POWER_ON):
00181             status = status + ":on"
00182     return "Power Management%s" % (status, )
00183 
00184 def iwconfig(interface):
00185     """ Get wireless information from the device driver. """
00186     if interface not in getWNICnames():
00187         print "%-8.16s  no wireless extensions." % (interface, )
00188     else:
00189         wifi = Wireless(interface)
00190         line = """%-8.16s  %s  """ % (interface, wifi.getWirelessName())
00191         if (wifi.getEssid()):
00192             line = line + """ESSID:"%s"  \n          """ % (wifi.getEssid(), )
00193         else:
00194             line = line + "ESSID:off/any  \n          "
00195 
00196         # Mode, Frequency, and Access Point
00197         line = line + "Mode:" + wifi.getMode()
00198         try:
00199             line = line + "  Frequency:" + wifi.getFrequency()
00200         except IOError, (error_number, error_string):
00201             # Some drivers do not return frequency info if not associated
00202             pass
00203 
00204         if (wifi.wireless_info.getMode() == pythonwifi.flags.IW_MODE_ADHOC):
00205             ap_type = "Cell"
00206         else:
00207             ap_type = "Access Point"
00208         ap_addr = wifi.getAPaddr()
00209         if (ap_addr == "00:00:00:00:00:00"):
00210             ap_addr = "Not-Associated"
00211         line = line + "  " + ap_type + ": " + ap_addr + "   "
00212         print line
00213 
00214         # Bit Rate, TXPower, and Sensitivity line
00215         line = "          "
00216         bitrate = getBitrate(wifi)
00217         if bitrate:
00218             line = line + bitrate
00219         txpower = getTXPower(wifi)
00220         if txpower:
00221             line = line + txpower
00222         sensitivity = getSensitivity(wifi)
00223         if sensitivity:
00224             line = line + sensitivity
00225         print line
00226 
00227         # Retry, RTS, and Fragmentation line
00228         line = "          "
00229         retry = getRetrylimit(wifi)
00230         if retry:
00231             line = line + retry
00232         rts = getRTS(wifi)
00233         if rts:
00234             line = line + rts
00235         fragment = getFragmentation(wifi)
00236         if fragment:
00237             line = line + fragment
00238         print line
00239 
00240         # Encryption line
00241         # line = "          "
00242         # line = line + getEncryption(wifi)
00243         # print line
00244 
00245         # Power Management line
00246         line = "          "
00247         line = line + getPowerManagement(wifi)
00248         print line
00249 
00250         try:
00251             stat, qual, discard, missed_beacon = wifi.getStatistics()
00252         except IOError, (error_number, error_string):
00253             # Some drivers do not return statistics info if not associated
00254             pass
00255         else:
00256             # Link Quality, Signal Level and Noise Level line
00257             line = "          "
00258             line = line + "Link Quality:%s/100  " % (qual.quality, )
00259             line = line + "Signal level:%sdBm  " % (qual.signallevel, )
00260             line = line + "Noise level:%sdBm" % (qual.noiselevel, )
00261             print line
00262             # Rx line
00263             line = "          "
00264             line = line + "Rx invalid nwid:%s  " % (discard['nwid'], )
00265             line = line + "Rx invalid crypt:%s  " % (discard['code'], )
00266             line = line + "Rx invalid frag:%s" % (discard['fragment'], )
00267             print line
00268             # Tx line
00269             line = "          "
00270             line = line + "Tx excessive retries:%s  " % (discard['retries'], )
00271             line = line + "Invalid misc:%s   " % (discard['misc'], )
00272             line = line + "Missed beacon:%s" % (missed_beacon, )
00273             print line
00274 
00275     print
00276 
00277 def setEssid(wifi, essid):
00278     """ Set the ESSID on the NIC. """
00279     try:
00280         wifi.setEssid(essid)
00281     except OverflowError, (errno, strerror):
00282         print "Error for wireless request \"Set ESSID\" (%X) :" % \
00283                 (pythonwifi.flags.SIOCSIWESSID, )
00284         print "    argument too big (max %d)" % \
00285                 (pythonwifi.flags.IW_ESSID_MAX_SIZE, )
00286     except Exception, detail:
00287         # Unexpected errors
00288         print detail
00289 
00290 def setMode(wifi, mode):
00291     """ Set the mode on the NIC. """
00292     try:
00293         wifi.setMode(mode)
00294     except ValueError, detail:
00295         print "Error for wireless request \"Set Mode\" (%X) :" % \
00296                 (pythonwifi.flags.SIOCSIWMODE, )
00297         print "    invalid argument \"%s\"." % (mode, )
00298     except IOError, (error_num, error_str):
00299         print "Error for wireless request \"Set Mode\" (%X) :" % \
00300                 (pythonwifi.flags.SIOCSIWMODE, )
00301         print "    SET failed on device %s ; %s." % (wifi.ifname, error_str)
00302     except Exception, detail:
00303         # Unexpected errors
00304         print type(detail), detail
00305 
00306 def setFreq(wifi, freq):
00307     """ Set the frequency on the NIC. """
00308     try:
00309         wifi.setFrequency(freq)
00310     except Exception, detail:
00311         # Unexpected errors
00312         print type(detail), detail
00313 
00314 def setKey(wifi, key):
00315     """ Set a WEP key on the NIC. """
00316     try:
00317         wifi.setKey(key)
00318     except Exception, detail:
00319         # Unexpected errors
00320         print type(detail), detail
00321 
00322 def setAP(wifi, ap):
00323     """ Set the AP with which to associate. """
00324     try:
00325         wifi.setAPaddr(ap)
00326     except Exception, detail:
00327         # Unexpected errors
00328         print type(detail), detail
00329 
00330 def usage():
00331     """ Print info about using iwconfig.py. """
00332     print """Usage: iwconfig.py [interface]
00333                 interface essid {NNN|any|on|off}
00334                 interface mode {managed|ad-hoc|master|...}
00335                 interface freq N.NNN[k|M|G]
00336                 interface channel N
00337                 interface bit {N[k|M|G]|auto|fixed}
00338                 interface rate {N[k|M|G]|auto|fixed}
00339                 interface enc {NNNN-NNNN|off}
00340                 interface key {NNNN-NNNN|off}
00341                 interface power {period N|timeout N|saving N|off}
00342                 interface nickname NNN
00343                 interface nwid {NN|on|off}
00344                 interface ap {N|off|auto}
00345                 interface txpower {NmW|NdBm|off|auto}
00346                 interface sens N
00347                 interface retry {limit N|lifetime N}
00348                 interface rts {N|auto|fixed|off}
00349                 interface frag {N|auto|fixed|off}
00350                 interface modulation {11g|11a|CCK|OFDMg|...}
00351                 interface commit 
00352        Check man pages for more details."""
00353 
00354 def version_info():
00355     """ Print version info for iwconfig.py, Wireless Extensions compatibility,
00356         and Wireless Extensions version in the kernel.
00357 
00358     """
00359     pass
00360 
00361 def get_matching_command(option):
00362     """ Return a function for the command.
00363 
00364         'option' -- string -- command to match
00365 
00366         Return None if no match found.
00367 
00368     """
00369     # build dictionary of commands and functions
00370     iwcommands = { "es"   : ("essid",      setEssid),
00371                    "mode" : ("mode",       setMode),
00372                    "fre"  : ("freq",       setFreq),
00373                    "ch"   : ("channel",    setFreq),
00374                    #"b"    : ("bit",        setBitrate),
00375                    #"ra"   : ("rate",       setBitrate),
00376                    "en"   : ("enc",        setKey),
00377                    "k"    : ("key",        setKey),
00378                    #"p"    : ("power",      setPower),
00379                    #"ni"   : ("nickname",   setNickname),
00380                    #"nw"   : ("nwid",       setNwid),
00381                    "a"    : ("ap",         setAP),
00382                    #"t"    : ("txpower",    setTxpower),
00383                    #"s"    : ("sens",       setSens),
00384                    #"re"   : ("retry",      setRetry),
00385                    #"rt"   : ("rts",        setRts),
00386                    #"fra"  : ("frag",       setFrag),
00387                    #"modu" : ("modulation", setModulation),
00388                    #"co"   : ("commit",     setCommit),
00389                  }
00390 
00391     function = None
00392     for command in iwcommands.keys():
00393         if option.startswith(command):
00394             if iwcommands[command][0].startswith(option):
00395                 function = iwcommands[command][1]
00396     return function
00397 
00398 def main():
00399     try:
00400         opts, args = getopt.getopt(sys.argv[1:], "hv", ["help", "version"])
00401     except getopt.GetoptError, error_str:
00402         # invalid options will be taken to be interface name
00403         pass
00404     else:
00405         try:
00406             if opts[0][0] in ("-h", "--help"):
00407                 usage()
00408         except:
00409             try:
00410                 if opts[0][0] in ("-v", "--version"):
00411                     version_info()
00412             except:
00413                 if len(args) == 0:
00414                     # no params given to iwconfig.py
00415                     for interface in getNICnames():
00416                         iwconfig(interface)
00417                 elif len(args) == 1:
00418                     # one param given to iwconfig.py, it should be a network device
00419                     if sys.argv[1] in getNICnames():
00420                         iwconfig(sys.argv[1])
00421                 else:
00422                     # more than one param, must be a command
00423                     # if program name and more than one argument are given
00424                     if len(sys.argv) > 2:
00425                         # Get the interface and command from command line
00426                         ifname, option = sys.argv[1:3]
00427                         # look for matching command
00428                         set_command = get_matching_command(option)
00429                         # if the second argument is a command
00430                         if set_command is not None:
00431                             wifi = Wireless(ifname)
00432                             set_command(wifi, sys.argv[3])
00433                         else:
00434                             print "iwconfig.py: unknown command `%s' " \
00435                                 "(check 'iwconfig.py --help')." % (option, )
00436 
00437 
00438 if __name__ == "__main__":
00439     main()


rocon_python_wifi
Author(s): Róman Joost, Sean Robinson
autogenerated on Fri May 2 2014 10:35:45