From 4e9e960ac943efe8091ff56cf1b319c7316b65e5 Mon Sep 17 00:00:00 2001
From: metrics <>
Date: Thu, 16 Aug 2007 01:07:26 +0000
Subject: [PATCH] Split the networking module, moving the common tasks into
wnettools.py
By splitting the common tasks performed by the networking module out
into a separate set of classes, it is possible to reduce code
duplication and improve the structure of the networking module.
The wnettools module now performs _almost_ all the actual commands that
control the network interfaces, splitting it from the actual connection
logic contained in the networking module. Splitting these two tasks also
allows for tool changes to be made in a central location, rather than
spread throughout the networking.py file.
---
daemon.py | 31 +-
gui.py | 2 +
networking.py | 1391 +++++++++++++++++++------------------------------
wnettools.py | 555 ++++++++++++++++++++
4 files changed, 1116 insertions(+), 863 deletions(-)
create mode 100644 wnettools.py
diff --git a/daemon.py b/daemon.py
index 009e9a0..4e22398 100644
--- a/daemon.py
+++ b/daemon.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2.5
+#!/usr/bin/env python
""" wicd - wireless connection daemon implementation.
This module implements the wicd daemon that provides network
@@ -312,7 +312,7 @@ class ConnectionWizard(dbus.service.Object):
print "no wired connection present, wired autoconnect failed"
print 'attempting to autoconnect to wireless network'
if self.GetWirelessInterface() != None:
- for x in self.LastScan:
+ for x, network in enumerate(self.LastScan):
if bool(self.LastScan[x]["has_profile"]):
print str(self.LastScan[x]["essid"]) + ' has profile'
if bool(self.LastScan[x].get('automatic')):
@@ -397,8 +397,7 @@ class ConnectionWizard(dbus.service.Object):
self.LastScan = scan
print 'scanning done'
print 'found',str(len(scan)),'networks:',
- for i in scan:
- print i,
+ for i, network in enumerate(scan):
self.ReadWirelessNetworkProfile(i)
print
#end function FreshScan
@@ -549,10 +548,10 @@ class ConnectionWizard(dbus.service.Object):
@dbus.service.method('org.wicd.daemon.wireless')
def CheckIfWirelessConnecting(self):
'''returns True if wireless interface is connecting, otherwise False'''
- if not self.wifi.ConnectingThread == None:
- #if ConnectingThread exists, then check for it's
+ if not self.wifi.connecting_thread == None:
+ #if connecting_thread exists, then check for it's
#status, if it doesn't, we aren't connecting
- status = self.wifi.ConnectingThread.IsConnecting
+ status = self.wifi.connecting_thread.is_connecting
print 'wireless connecting',status
return status
else:
@@ -571,8 +570,8 @@ class ConnectionWizard(dbus.service.Object):
@dbus.service.method('org.wicd.daemon.wireless')
def CheckWirelessConnectingMessage(self):
'''returns the wireless interface's status message'''
- if not self.wifi.ConnectingThread == None:
- stat = self.wifi.ConnectingThread.GetStatus()
+ if not self.wifi.connecting_thread == None:
+ stat = self.wifi.connecting_thread.GetStatus()
print 'wireless connect status',stat
return stat
else:
@@ -584,8 +583,8 @@ class ConnectionWizard(dbus.service.Object):
def CancelConnect(self):
'''cancels the wireless connection attempt'''
print 'canceling connection attempt'
- if not self.wifi.ConnectingThread == None:
- self.wifi.ConnectingThread.ShouldDie = True
+ if not self.wifi.connecting_thread == None:
+ self.wifi.connecting_thread.ShouldDie = True
misc.Run("killall dhclient dhclient3 wpa_supplicant")
#end function CancelConnect
@@ -603,10 +602,10 @@ class ConnectionWizard(dbus.service.Object):
@dbus.service.method('org.wicd.daemon.wired')
def CheckIfWiredConnecting(self):
'''returns True if wired interface is connecting, otherwise False'''
- if not self.wired.ConnectingThread == None:
- #if ConnectingThread exists, then check for it's
+ if not self.wired.connecting_thread == None:
+ #if connecting_thread exists, then check for it's
#status, if it doesn't exist, we aren't connecting
- status = self.wired.ConnectingThread.IsConnecting
+ status = self.wired.connecting_thread.is_connecting
print 'wired connecting',status
return status
else:
@@ -662,8 +661,8 @@ class ConnectionWizard(dbus.service.Object):
@dbus.service.method('org.wicd.daemon.wired')
def CheckWiredConnectingMessage(self):
'''returns the wired interface\'s status message'''
- if not self.wired.ConnectingThread == None:
- status = self.wired.ConnectingThread.GetStatus()
+ if not self.wired.connecting_thread == None:
+ status = self.wired.connecting_thread.GetStatus()
print 'wired connect status',status
return status
else:
diff --git a/gui.py b/gui.py
index f89f78a..293a37c 100644
--- a/gui.py
+++ b/gui.py
@@ -1232,10 +1232,12 @@ class appGui:
wired.SetWiredProperty("gateway",'')
if networkentry.expander.checkboxStaticDNS.get_active() == True:
+ wireless.SetWirelessProperty(networkid,'use_static_dns',True)
wired.SetWiredProperty("dns1",noneToString(networkentry.expander.txtDNS1.get_text()))
wired.SetWiredProperty("dns2",noneToString(networkentry.expander.txtDNS2.get_text()))
wired.SetWiredProperty("dns3",noneToString(networkentry.expander.txtDNS3.get_text()))
else:
+ wireless.SetWirelessProperty(networkid,'use_static_dns',False)
wired.SetWiredProperty("dns1",'')
wired.SetWiredProperty("dns2",'')
wired.SetWiredProperty("dns3",'')
diff --git a/networking.py b/networking.py
index 720e99a..51483f3 100644
--- a/networking.py
+++ b/networking.py
@@ -1,923 +1,620 @@
-## THE NETWORKING CLASS
-## WRITTEN DECEMBER 18TH, 2006
-## RELEASED UNDER THE GNU General Public License
+#!/usr/bin/env python
+""" networking - Provides wrappers for common network operations
-## WRITTEN IN PYTHON, CAN NOT BE USED ALONE
-## MUST BE IMPORTED VIA import networking
-## TO ANOTHER PROJECT IF YOU WISH TO USE IT
+This module provides wrappers of the common network tasks as well as
+threads to perform the actual connecting to networks.
+
+class Controller() -- Parent class to Wireless and Wired
+class ConnectThread() -- Parent class to WirelessConnectThread and
+ WiredConnectThread
+class Wireless() -- Wrapper for various wireless functions
+class Wired() -- Wrapper for various wired functions
+class WirelessConnectThread() -- Connection thread for wireless
+ interface
+class WiredConnectThread() -- Connection thread for wired
+ interface
+
+"""
+
+#
+# Copyright (C) 2007 Adam Blackburn
+# Copyright (C) 2007 Dan O'Reilly
+# Copyright (C) 2007 Byron Hillis
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License Version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+#
+
+#
+# Much thanks to wieman01 for help and support with various types of encyption
+# Also thanks to foxy123, yopnono, and the many others who reported bugs helped
+# and helped keep this project moving
+#
import os
import sys
+import re
+import sys
+import threading
+import thread
+import operator
+import misc
+import wnettools
import wpath
+
if __name__ == '__main__':
wpath.chdir(__file__)
-# Import the library of random functions that we need here
-# this is also written by me, for this purpose
-import misc
-# Import some other random libraries that we're gonna need.
-import re,threading,thread
-# Much thanks to wieman01 for help and support with various types of encyption
-# also thanks to foxy123, yopnono, and the many others who reported bugs helped
-# and helped keep this project moving.
-
-class Wireless:
+class Controller(object):
+ """ Parent class for the different interface types. """
wireless_interface = None
wired_interface = None
- wpa_driver = None
- ConnectingThread = None
+ connecting_thread = None
before_script = None
after_script = None
disconnect_script = None
- # Create a function to scan for wireless networks
+
+
+class ConnectThread(threading.Thread):
+ """ A class to perform network connections in a multi-threaded way.
+
+ Useless on it's own, this class provides the generic functions
+ necessary for connecting using a separate thread. """
+
+ is_connecting = None
+ connecting_thread = None
+ should_die = False
+ lock = thread.allocate_lock()
+
+
+ def __init__(self, network, wireless, wired,
+ before_script, after_script, disconnect_script, gdns1,
+ gdns2, gdns3):
+ """ Initialise the required object variables and the thread.
+
+ Keyword arguments:
+ network -- the network to connect to
+ wireless -- name of the wireless interface
+ wired -- name of the wired interface
+ before_script -- script to run before bringing up the interface
+ after_script -- script to run after bringing up the interface
+ disconnect_script -- script to run after disconnection
+ gdns1 -- global DNS server 1
+ gdns2 -- global DNS server 2
+ gdns3 -- global DNS server 3
+
+ """
+ threading.Thread.__init__(self)
+ self.network = network
+ self.wireless_interface = wireless
+ self.wired_interface = wired
+ self.is_connecting = False
+ self.before_script = before_script
+ self.after_script = after_script
+ self.disconnect_script = disconnect_script
+
+ self.global_dns_1 = gdns1
+ self.global_dns_2 = gdns2
+ self.global_dns_3 = gdns3
+
+ self.SetStatus('interface_down')
+
+
+ def SetStatus(self, status):
+ """ Set the threads current status message in a thread-safe way.
+
+ Keyword arguments:
+ status -- the current connection status
+
+ """
+ self.lock.acquire()
+ self.connecting_message = status
+ self.lock.release()
+
+
+ def GetStatus(self):
+ """ Get the threads current status message in a thread-safe way.
+
+ Returns:
+ The current connection status.
+
+ """
+ self.lock.acquire()
+ message = self.connecting_message
+ self.lock.release()
+ return message
+
+
+
+class Wireless(Controller):
+ """ A wrapper for common wireless interface functions. """
+
+ wpa_driver = None
+
def Scan(self,essid=None):
- # We ask for an essid, because then we can see hidden networks
+ """ Scan for available wireless networks.
- #####
- ## DECLARE THE REGEX PATTERNS
- #####
+ Keyword arguments:
+ essid -- The essid of a hidden network
- # Init the regex patterns that will be used to search the output of
- # iwlist scan for info.
- # These are well tested, should work on most cards.
- essid_pattern = re.compile('.*ESSID:"(.*?)"\n',re.DOTALL | re.I | re.M |
- re.S)
- ap_mac_pattern = re.compile('.*Address: (.*?)\n',re.DOTALL | re.I |
- re.M | re.S)
- channel_pattern = re.compile('.*Channel:? ?(\d\d?)',re.DOTALL | re.I |
- re.M | re.S)
- strength_pattern = re.compile('.*Quality:?=? ?(\d\d*)',re.DOTALL |
- re.I | re.M | re.S)
- altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)',
- re.DOTALL | re.I | re.M | re.S)
- mode_pattern = re.compile('.*Mode:(.*?)\n',re.DOTALL | re.I | re.M |
- re.S)
- freq_pattern = re.compile('.*Frequency:(.*?)\n',re.DOTALL | re.I |
- re.M | re.S)
+ Returns:
+ A list of available networks sorted by strength.
- wep_pattern = re.compile('.*Encryption key:(.*?)\n',re.DOTALL | re.I |
- re.M | re.S)
- altwpa_pattern = re.compile('(wpa_ie)',re.DOTALL | re.I | re.M | re.S)
- wpa1_pattern = re.compile('(WPA Version 1)',re.DOTALL | re.I | re.M |
- re.S)
- wpa2_pattern = re.compile('(WPA2)',re.DOTALL | re.I | re.M | re.S)
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface,
+ self.wpa_driver)
- #####
- ## PREPARE THE INTERFACE
- #####
-
- # Prepare the interface for scanning.
- # Note that this must be run as root, otherwise we're gonna have trouble
- misc.Run('ifconfig ' + self.wireless_interface + ' up')
+ # Prepare the interface for scanning
+ wiface.Up()
+ # If there is a hidden essid then set it now, so that when it is
+ # scanned it will be recognized.
essid = misc.Noneify(essid)
- if not essid is None:
- # If there is a hidden essid, we need to tell the computer what it
- # is. Then when it is scanned it will be recognized.
- print "setting hidden essid..." + essid
- misc.Run('iwconfig ' + self.wireless_interface + ' essid "' +
- essid + '"')
+ if not essid == None:
+ print 'Setting hidden essid' + essid
+ wiface.SetEssid(essid)
- #####
- ## RUN THE SCAN
- #####
-
- # Run iwlist scan and get the avaliable networks and
- # save them to scan_data - all in one big string
- scandata = misc.Run('iwlist ' + self.wireless_interface + ' scan')
-
- #####
- ## PROCESS THE DATA
- #####
-
- # Split the networks apart, using Cell as our split point
- # this way we can look at only one network at a time
- networks = scandata.split( ' Cell ' )
-
- # Declare
- i=0
- # Make an array for the aps
- aps = {}
- for cell in networks:
- # Search to see if there is an essid in this section
- # if there isn't, that means that it is useless
- # so we don't use it then.
-
- # Set essid to the value, this is just a temp variable
- if cell.count("ESSID:") > 0:
- # Since an essid was found
- # we will extract the rest of the info
- # make a dictionary for the data
- CurrentNetwork = {}
-
- # Use the RunRegex function to neaten up our code
- # all it does for us is run the regex on the string
- # and return the result,
- # but it makes this code look pretty.
-
- CurrentNetwork["essid"] = misc.RunRegex(essid_pattern,cell)
-
- if CurrentNetwork["essid"] == "":
- CurrentNetwork["hidden"] = True
- # Change the name so it doesn't screw stuff up
- # because it looks like HTML - GTK no like
- CurrentNetwork["essid"] = "Hidden"
- else:
- CurrentNetwork["hidden"] = False
-
- CurrentNetwork["channel"] = misc.RunRegex(channel_pattern,cell)
- # Some cards don't show the channel number, so we try
- # assigning the number based on the frequency returned.
- if CurrentNetwork["channel"] is None:
- freq = misc.RunRegex(freq_pattern,cell)
- if freq == '2.412 GHz':
- CurrentNetwork["channel"] = 1
- elif freq == '2.417 GHz':
- CurrentNetwork["channel"] = 2
- elif freq == '2.422 GHz':
- CurrentNetwork["channel"] = 3
- elif freq == '2.427 GHz':
- CurrentNetwork["channel"] = 4
- elif freq == '2.432 GHz':
- CurrentNetwork["channel"] = 5
- elif freq == '2.437 GHz':
- CurrentNetwork["channel"] = 6
- elif freq == '2.442 GHz':
- CurrentNetwork["channel"] = 7
- elif freq == '2.447 GHz':
- CurrentNetwork["channel"] = 8
- elif freq == '2.452 GHz':
- CurrentNetwork["channel"] = 9
- elif freq == '2.457 GHz':
- CurrentNetwork["channel"] = 10
- elif freq == '2.462 GHz':
- CurrentNetwork["channel"] = 11
- elif freq == '2.467 GHz':
- CurrentNetwork["channel"] = 12
- elif freq == '2.472 GHz':
- CurrentNetwork["channel"] = 13
- elif freq == '2.484 GHz':
- CurrentNetwork["channel"] = 14
- else: # Must be a really crappy driver. :(
- print 'Couldn\'t determine channel number for \
- current network'
-
- CurrentNetwork["bssid"] = misc.RunRegex(ap_mac_pattern,cell)
- print " ##### " + CurrentNetwork["bssid"]
- CurrentNetwork["mode"] = misc.RunRegex(mode_pattern,cell)
-
- # Since encryption needs a True or False,
- # we have to do a simple if then to set it
- if misc.RunRegex(wep_pattern,cell) == "on":
- if self.wpa_driver != 'ralink legacy':
- CurrentNetwork["encryption"] = True
- # Set this, because if it is something else this will
- # be overwritten.
- CurrentNetwork["encryption_method"] = "WEP"
-
- if misc.RunRegex(wpa1_pattern,cell) == "WPA Version 1":
- CurrentNetwork["encryption_method"] = "WPA"
-
- if misc.RunRegex(altwpa_pattern,cell) == "wpa_ie":
- CurrentNetwork["encryption_method"] = "WPA"
-
- if misc.RunRegex(wpa2_pattern,cell) == "WPA2":
- CurrentNetwork["encryption_method"] = "WPA2"
-
- # Support for ralink legacy drivers (maybe only
- # serialmonkey enhanced), may not work w/ hidden networks.
- else:
- iwpriv = misc.Run("iwpriv " + self.wireless_interface +
- " get_site_survey")
- lines = iwpriv.splitlines()
- lines = lines[2:]
- for x in lines:
- info = x.split()
- # Make sure we read in a valid entry
- if len(info) < 5 or info is None or info == '':
- break;
- # We've found the network we want to connect to
- if info[2] == CurrentNetwork["essid"]:
- CurrentNetwork["encryption"] = True
- if info[5] == 'WEP' or ((info[5] == 'OPEN' or
- info[5] == 'SHARED') and info[4] == 'WEP'):
- CurrentNetwork["encryption_method"] = 'WEP'
- elif info[5] == 'WPA-PSK':
- CurrentNetwork["encryption_method"] = 'WPA'
- elif info[5] == 'WPA2-PSK':
- CurrentNetwork["encryption_method"] = 'WPA2'
- else:
- print 'Unknown AuthMode, can\'t assign \
- encryption_method!!'
- CurrentNetwork["encryption_method"] = \
- 'Unknown'
- # Set signal strength here
- # (not link quality! dBm vs %)
- CurrentNetwork["quality"] = info[1][1:]
- else:
- CurrentNetwork["encryption"] = False
- # End If
-
- if self.wpa_driver != 'ralink legacy':
- # Since strength needs a -1 if the quality isn't found
- # we need a simple if then to set it
- if misc.RunRegex(strength_pattern,cell):
- CurrentNetwork["quality"] = misc.RunRegex(
- strength_pattern,cell)
- # Alternate way of labeling link quality
- elif misc.RunRegex(altstrength_pattern,cell):
- CurrentNetwork["quality"] = misc.RunRegex(
- altstrength_pattern,
- cell)
- else:
- CurrentNetwork["quality"] = -1
-
- # Add this network to the list of networks
- aps[ i ] = CurrentNetwork
- # Now increment the counter
- i+=1
- # End For
-
- # Run a bubble sort to list networks by signal strength
- going = True
-
- while going:
- sorted = False
- for i in aps:
- # Set x to the current number
- x = int(i)
- # Set y to the next number
- y = int(i+1)
-
- # Only run this if we actually have another element after
- # the current one.
- if (len(aps) > i+1):
-
- # Move around depending on qualities.
- # We want the lower qualities at the bottom of the list,
- # so we check to see if the quality below the current one
- # is higher the current one. If it is, we swap them.
-
- if (int(aps[int(y)]["quality"]) >
- int(aps[int(x)]["quality"])):
- # Set sorted to true so we don't exit
- sorted=True
- # Do the move
- temp=aps[y]
- aps[y]=aps[x]
- aps[x]=temp
- # End If
- # End If
- # End For
-
- if (sorted == False):
- going = False
- # End If
- # End While
-
- #return the list of sorted access points
+ aps = wiface.GetNetworks()
+ aps.sort(key=lambda x: x['quality'])
+ aps.reverse()
return aps
- # End Function Scan
- def Connect(self,network):
- #call the thread, so we don't hang up the entire works
- self.ConnectingThread = self.ConnectThread(network,
- self.wireless_interface, self.wired_interface,
- self.wpa_driver, self.before_script,
- self.after_script, self.disconnect_script,
- self.global_dns_1, self.global_dns_2,
- self.global_dns_3)
- self.ConnectingThread.start()
+ def Connect(self, network):
+ """ Spawn a connection thread to connect to the network.
+
+ Keyword arguments:
+ network -- network to connect to
+
+ """
+ self.connecting_thread = WirelessConnectThread(network,
+ self.wireless_interface, self.wired_interface,
+ self.wpa_driver, self.before_script, self.after_script,
+ self.disconnect_script, self.global_dns_1,
+ self.global_dns_2, self.global_dns_3)
+ self.connecting_thread.start()
return True
- class ConnectThread(threading.Thread):
- IsConnecting = None
- ConnectingMessage = None
- ShouldDie = False
- lock = thread.allocate_lock()
-
- def __init__(self, network, wireless, wired, wpa_driver, before_script,
- after_script, disconnect_script, gdns1, gdns2, gdns3):
- threading.Thread.__init__(self)
- self.network = network
- self.wireless_interface = wireless
- self.wired_interface = wired
- self.wpa_driver = wpa_driver
- self.IsConnecting = False
- self.before_script = before_script
- self.after_script = after_script
- self.disconnect_script = disconnect_script
-
- self.global_dns_1 = gdns1
- self.global_dns_2 = gdns2
- self.global_dns_3 = gdns3
-
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'interface_down'
- finally:
- self.lock.release()
- #lock = thread.allocate_lock()
-
- def GetStatus(self):
- print "status request"
- print "acqlock",self.lock.acquire()
- try:
- print " ...lock acquired..."
- message = self.ConnectingMessage
- finally:
- self.lock.release()
- print " ...lock released..."
- return message
-
- def run(self):
- # Note that we don't put the wired interface down,
- # but we do flush all wired entries from the routing table
- # so it shouldn't be used at all.
-
- self.IsConnecting = True
- network = self.network
-
- # Execute pre-connection script if necessary.
- if self.before_script != '' and self.before_script != None:
- print 'Executing pre-connection script'
- print misc.Run('./run-script.py ' + self.before_script)
-
- # Put it down
- print "interface down..."
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'interface_down'
- finally:
- self.lock.release()
- misc.Run("ifconfig " + self.wireless_interface + " down")
-
- # Set a false ip so that when we set the real one, the correct
- # routing entry is created.
- print "Setting false ip..."
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'resetting_ip_address'
- finally:
- self.lock.release()
-
- misc.Run("ifconfig " + self.wired_interface + " 0.0.0.0")
- misc.Run("ifconfig " + self.wireless_interface + " 0.0.0.0")
-
- print "killing wpa_supplicant, dhclient, dhclient3"
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'removing_old_connection'
- finally:
- self.lock.release()
-
- misc.Run("killall dhclient dhclient3 wpa_supplicant")
-
- # Check to see if we need to generate a PSK
- if self.wpa_driver != "ralink legacy":
- if not network.get('key') is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'generating_psk'
- finally:
- self.lock.release()
-
- print "generating psk..."
- key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*',
- re.DOTALL | re.I | re.M | re.S)
- network["psk"] = misc.RunRegex(key_pattern,
- misc.Run('wpa_passphrase "' +
- network["essid"] + '" "' +
- network["key"] + '"'))
- # Generate the wpa_supplicant file...
- if not network.get('enctype') is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'generating_wpa_config'
- finally:
- self.lock.release()
-
- print "generating wpa_supplicant configuration file..."
- misc.ParseEncryption(network)
- wpa_string = ("wpa_supplicant -B -i " +
- self.wireless_interface +
- " -c " + "\"" + wpath.networks +
- network["bssid"].replace(":","").lower() +
- "\" -D " + self.wpa_driver)
- print wpa_string
- misc.Run(wpa_string)
-
- print "flushing the routing table..."
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'flushing_routing_table'
- finally:
- self.lock.release()
-
- misc.Run("ip route flush dev " + self.wireless_interface)
- misc.Run("ip route flush dev " + self.wired_interface)
-
- print "configuring the wireless interface..."
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'configuring_interface'
- finally:
- self.lock.release()
-
- # Bring it up
- print "interface up..."
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'interface_up'
- finally:
- self.lock.release()
-
- print misc.Run("ifconfig " + self.wireless_interface + " up")
-
- if network["mode"].lower() == "master":
- misc.Run("iwconfig " + self.wireless_interface +
- " mode managed")
- else:
- misc.Run("iwconfig " + self.wireless_interface + " mode " +
- network["mode"])
-
- misc.Run("iwconfig " + self.wireless_interface + " essid \"" +
- network["essid"] + "\" channel " + str(network["channel"])
- + " ap " + network["bssid"])
-
- # Adds support for ralink cards that can't use wpasupplicant
- if self.wpa_driver == "ralink legacy":
- if network.get('key') != None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_encryption_info'
- finally:
- self.lock.release()
-
- print 'setting up ralink encryption'
- iwpriv = misc.Run("iwpriv " + self.wireless_interface +
- " get_site_survey")
- lines = iwpriv.splitlines()
- lines = lines[2:]
- for x in lines:
- info = x.split()
- if len(info) < 5 or info is None or info == '':
- break;
- if info[2] == network.get("essid"):
- if info[5] == 'WEP' or (info[5] == 'OPEN'
- and info[4] == 'WEP'):
- print 'setting up WEP'
- misc.Run("iwconfig " + self.wireless_interface +
- " key " + network.get('key'))
- elif info[5] == 'SHARED' and info[4] == 'WEP':
- print 'setting up WEP'
- misc.Run("iwpriv " + self.wireless_interface +
- " set NetworkType=" + info[6])
- misc.Run("iwpriv " + self.wireless_interface +
- " set AuthMode=SHARED")
- misc.Run("iwpriv " + self.wireless_interface +
- " set EncrypType=" + info[4])
- misc.Run("iwpriv " + self.wireless_interface +
- " set Key1=" + network.get('key'))
- misc.Run("iwpriv " + self.wireless_interface +
- " set DefaultKeyID=1")
- misc.Run("iwpriv " + self.wireless_interface +
- " set SSID=" + info[2])
- elif info[5] == 'WPA-PSK':
- print 'setting up WPA-PSK'
- misc.Run("iwpriv " + self.wireless_interface +
- " set NetworkType=" + info[6])
- misc.Run("iwpriv " + self.wireless_interface +
- " set AuthMode=WPAPSK")
- misc.Run("iwpriv " + self.wireless_interface +
- " set EncrypType=" + info[4])
- misc.Run("iwpriv " + self.wireless_interface +
- " set SSID=" + info[2])
- misc.Run("iwpriv " + self.wireless_interface +
- " set WPAPSK=" + network.get('key'))
- misc.Run("iwpriv " + self.wireless_interface +
- " set SSID=" + info[2])
- elif info[5] == 'WPA2-PSK':
- print 'setting up WPA2-PSK'
- misc.Run("iwpriv " + self.wireless_interface +
- " set NetworkType=" + info[6])
- misc.Run("iwpriv " + self.wireless_interface +
- " set AuthMode=WPA2PSK")
- misc.Run("iwpriv " + self.wireless_interface +
- " set EncrypType=" + info[4])
- misc.Run("iwpriv " + self.wireless_interface +
- " set SSID=" + info[2])
- misc.Run("iwpriv " + self.wireless_interface +
- " set WPAPSK=" + network.get('key'))
- misc.Run("iwpriv " + self.wireless_interface +
- " set SSID=" + info[2])
- else:
- print 'Unknown AuthMode, can\'t complete \
- connection process!!!'
- print "done setting encryption info"
-
- if not network.get('broadcast') is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_broadcast_address'
- finally:
- self.lock.release()
-
-
- print "setting the broadcast address..." + network["broadcast"]
- misc.Run("ifconfig " + self.wireless_interface + " broadcast " +
- network["broadcast"])
-
- if not network.get("dns1") is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_static_dns'
- finally:
- self.lock.release()
-
- print "setting the first dns server...", network["dns1"]
- resolv = open("/etc/resolv.conf","w")
- misc.WriteLine(resolv,"nameserver " + network["dns1"])
- if not network.get("dns2") is None:
- print "setting the second dns server...", network["dns2"]
- misc.WriteLine(resolv,"nameserver " + network["dns2"])
- if not network.get("dns3") is None:
- print "setting the third dns server..."
- misc.WriteLine(resolv,"nameserver " + network["dns3"])
-
- if not network.get('ip') is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_static_ip'
- finally:
- self.lock.release()
-
- print "setting static ips..."
- misc.Run("ifconfig " + self.wireless_interface + " " +
- network["ip"] )
- misc.Run("ifconfig " + self.wireless_interface + " netmask " +
- network["netmask"] )
- print "adding default gateway..." + network["gateway"]
- misc.Run("route add default gw " + network["gateway"])
- else:
- #run dhcp...
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'running_dhcp'
- finally:
- self.lock.release()
-
- print "running dhcp..."
- if not self.ShouldDie:
- misc.Run("dhclient " + self.wireless_interface)
-
- # Code repetition --- bad.
- # However, I think this is the best way.
-
- if (network.get('use_static_dns') == True and
- network.get('use_global_dns') == False):
- # Just using normal dns
- if not network.get("dns1") is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_static_dns'
- finally:
- self.lock.release()
- print "setting the first dns server...", network["dns1"]
- resolv = open("/etc/resolv.conf","w")
- misc.WriteLine(resolv,"nameserver " + network["dns1"])
- if not network.get("dns2") is None:
- print "setting the second dns server...",network["dns2"]
- misc.WriteLine(resolv,"nameserver " + network["dns2"])
- if not network.get("dns3") is None:
- print "setting the third dns server..."
- misc.WriteLine(resolv,"nameserver " + network["dns3"])
- resolv.close()
-
- if (network.get('use_static_dns') == True and
- network.get('use_global_dns') == True):
- # Using static dns
- if not self.global_dns_1 is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_static_dns'
- finally:
- self.lock.release()
- print "setting the first dns server...", self.global_dns_1
- resolv = open("/etc/resolv.conf","w")
- misc.WriteLine(resolv,"nameserver " + self.global_dns_1)
- if not misc.Noneify(self.global_dns_2) is None:
- print "setting the second dns server...",\
- self.global_dns_2
- misc.WriteLine(resolv,"nameserver " + self.global_dns_2)
- if not misc.Noneify(self.global_dns_3) is None:
- print "setting the third dns server..."
- misc.WriteLine(resolv,"nameserver " + self.global_dns_3)
- resolv.close()
-
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'done'
- finally:
- self.lock.release()
-
- print "done"
- self.IsConnecting = False
-
- # Execute post-connection script if necessary.
- if self.after_script != '' and self.after_script != None:
- print 'executing post connection script'
- print misc.Run('./run-script.py ' + self.after_script)
- # End function Connect
- # End class Connect
def GetSignalStrength(self):
- output = misc.Run("iwconfig " + self.wireless_interface)
- strength_pattern = re.compile('.*Quality:?=? ?(\d+)',re.DOTALL | re.I
- | re.M | re.S)
- altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)',re.DOTALL
- | re.I | re.M | re.S)
- strength = misc.RunRegex(strength_pattern,output)
- if strength is None:
- strength = misc.RunRegex(altstrength_pattern,output)
- return strength
- # End function GetSignalStrength
+ """ Get signal strength of the current network.
+
+ Returns:
+ The current signal strength.
+
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface, self.wpa_driver)
+ return wiface.GetSignalStrength()
+
def GetCurrentNetwork(self):
- output = misc.Run("iwconfig " + self.wireless_interface)
- essid_pattern = re.compile('.*ESSID:"(.*?)"',re.DOTALL | re.I | re.M
- | re.S)
- return misc.RunRegex(essid_pattern,output)
- # End function GetCurrentNetwork
+ """ Get current network name.
+
+ Returns:
+ The name of the currently connected network.
+
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface, self.wpa_driver)
+ return wiface.GetCurrentNetwork()
+
def GetIP(self):
- output = misc.Run("ifconfig " + self.wireless_interface)
- ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S)
- return misc.RunRegex(ip_pattern,output)
- # End function GetIP
+ """ Get the IP of the interface.
- def CreateAdHocNetwork(self,essid,channel,ip,enctype,key,encused,ics):
- # Remove wpa_supplicant, as it can cause the connection to revert to
- # previous networks...
- misc.Run("killall dhclient dhclient3 wpa_supplicant")
- misc.Run('ifconfig ' + self.wireless_interface + ' down')
- misc.Run('iwconfig ' + self.wireless_interface + ' mode ad-hoc')
- misc.Run('iwconfig ' + self.wireless_interface + ' channel ' + channel)
- misc.Run('iwconfig ' + self.wireless_interface + ' essid ' + essid)
- # Right now it just assumes you're using WEP
- if encused == True:
- misc.Run('iwconfig ' + self.wireless_interface + ' key ' + key)
+ Returns:
+ The IP address of the interface in dotted notation.
- misc.Run('ifconfig ' + self.wireless_interface + ' up')
- misc.Run('ifconfig ' + self.wireless_interface + ' inet ' + ip)
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface, self.wpa_driver)
+ return wiface.GetIP()
- # Also just assume that the netmask is 255.255.255.0, it simplifies ICS.
- misc.Run('ifconfig ' + self.wireless_interface +
- ' netmask 255.255.255.0')
+
+ def CreateAdHocNetwork(self, essid, channel, ip, enctype, key,
+ enc_used, ics):
+ """ Create an ad-hoc wireless network.
+
+ Keyword arguments:
+ essid -- essid of the ad-hoc network
+ channel -- channel of the ad-hoc network
+ ip -- ip of the ad-hoc network
+ enctype -- unused
+ key -- key of the ad-hoc network
+ enc_used -- encrytion enabled on ad-hoc network
+ ics -- enable internet connection sharing
+
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface, self.wpa_driver)
+ wiface.StopDHCP()
+ wiface.StopWPA()
+ wiface.Down()
+ wiface.SetMode('ad-hoc')
+ wiface.SetChannel(channel)
+ wiface.SetEssid(essid)
+ #Right now it just assumes you're using WEP
+ if enc_used == True:
+ wiface.SetKey(key)
+
+ wiface.Up()
+ # Just assume that the netmask is 255.255.255.0, it simplifies ICS
+ wiface.SetAddress(ip, '255.255.255.0')
ip_parts = misc.IsValidIP(ip)
if ics and ip_parts:
# Set up internet connection sharing here
- # flush the forward tables
+ # Flush the forward tables
misc.Run('iptables -F FORWARD')
misc.Run('iptables -N fw-interfaces')
misc.Run('iptables -N fw-open')
misc.Run('iptables -F fw-interfaces')
misc.Run('iptables -F fw-open')
- misc.Run('iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN \
- -j TCPMSS --clamp-mss-to-pmtu')
- misc.Run('iptables -A FORWARD -m state --state RELATED,ESTABLISHED \
- -j ACCEPT')
+ misc.Run('iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu')
+ misc.Run('iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT')
misc.Run('iptables -A FORWARD -j fw-interfaces ')
misc.Run('iptables -A FORWARD -j fw-open ')
- misc.Run('iptables -A FORWARD -j REJECT --reject-with \
- icmp-host-unreachable')
+ misc.Run('iptables -A FORWARD -j REJECT --reject-with icmp-host-unreachable')
misc.Run('iptables -P FORWARD DROP')
- misc.Run('iptables -A fw-interfaces -i ' + self.wireless_interface +
- ' -j ACCEPT')
- basic_ip = '.'.join(ip_parts[0:3]) + '.0' # Not sure that basic_ip is a good name
- misc.Run('iptables -t nat -A POSTROUTING -s ' + basic_ip +
- '/255.255.255.0 -o ' + self.wired_interface +
- ' -j MASQUERADE')
+ misc.Run('iptables -A fw-interfaces -i ' + self.wireless_interface + ' -j ACCEPT')
+ net_ip = '.'.join(ip_parts[0:3]) + '.0'
+ misc.Run('iptables -t nat -A POSTROUTING -s ' + net_ip + '/255.255.255.0 -o ' + self.wired_interface + ' -j MASQUERADE')
misc.Run('echo 1 > /proc/sys/net/ipv4/ip_forward') # Enable routing
- # End function CreateAdHocNetwork
+
def DetectWirelessInterface(self):
- return misc.RunRegex(re.compile('(\w*)\s*\w*\s*[a-zA-Z0-9.-_]*\s*(?=ESSID)',
- re.DOTALL | re.I | re.M | re.S),
- misc.Run("iwconfig"))
+ """ Detect available wireless interfaces.
+
+ Returns:
+ The first available wireless interface.
+
+ """
+ wnettools.GetWirelessInterfaces()
+
def Disconnect(self):
+ """ Disconnect from the network. """
+ wiface = wnettools.WirelessInterface(self.wireless_interface, self.wpa_driver)
if self.disconnect_script != None:
- print 'running wireless network disconnect script'
+ print 'Running wireless network disconnect script'
misc.Run(self.disconnect_script)
- misc.Run('ifconfig ' + self.wireless_interface + ' 0.0.0.0')
- misc.Run('ifconfig ' + self.wireless_interface + ' down')
+
+ wiface.SetAddress('0.0.0.0')
+ wiface.Down()
-# End class Wireless
-class Wired:
+class WirelessConnectThread(ConnectThread):
+ """ A thread class to perform the connection to a wireless network.
- wireless_interface = None
- wired_interface = None
- ConnectingThread = None
- before_script = None
- after_script = None
- disconnect_script = None
+ This thread, when run, will perform the necessary steps to connect
+ to the specified network.
- def GetIP(self):
- output = misc.Run("ifconfig " + self.wired_interface)
- ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S)
- return misc.RunRegex(ip_pattern,output)
+ """
+
+ def __init__(self, network, wireless, wired, wpa_driver,
+ before_script, after_script, disconnect_script, gdns1,
+ gdns2, gdns3):
+ """ Initialise the thread with network information.
+
+ Keyword arguments:
+ network -- the network to connect to
+ wireless -- name of the wireless interface
+ wired -- name of the wired interface
+ wpa_driver -- type of wireless interface
+ before_script -- script to run before bringing up the interface
+ after_script -- script to run after bringing up the interface
+ disconnect_script -- script to run after disconnection
+ gdns1 -- global DNS server 1
+ gdns2 -- global DNS server 2
+ gdns3 -- global DNS server 3
+
+ """
+ ConnectThread.__init__(self, network, wireless, wired,
+ before_script, after_script, disconnect_script, gdns1,
+ gdns2, gdns3)
+ self.wpa_driver = wpa_driver
+
+
+ def run(self):
+ """ The main function of the connection thread.
+
+ This function performs the necessary calls to connect to the
+ specified network, using the information provided. The following
+ indicates the steps taken.
+ 1. Run pre-connection script.
+ 2. Take down the interface and clean up any previous
+ connections.
+ 3. Generate a PSK if required and authenticate.
+ 4. Associate with the WAP.
+ 5. Get/set IP address and DNS servers.
+
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface, self.wpa_driver)
+ liface = wnettools.WiredInterface(self.wired_interface)
+
+ self.is_connecting = True
+
+ # Execute pre-connection script if necessary
+ if self.before_script != '' and self.before_script != None:
+ print 'Executing pre-connection script'
+ print misc.Run('run-script.py ' + self.before_script)
+
+ # Put it down
+ print 'Interface down'
+ self.SetStatus('interface_down')
+ wiface.Down()
+
+ # Set a false ip so that when we set the real one, the correct
+ # routing entry is created
+ print 'Setting false IP...'
+ self.SetStatus('resetting_ip_address')
+ wiface.SetAddress('0.0.0.0')
+ liface.SetAddress('0.0.0.0')
+
+ print 'Stopping wpa_supplicant, dhclient, dhclient3'
+ wiface.StopDHCP()
+ wiface.StopWPA()
+ liface.StopDHCP()
+
+ # Check to see if we need to generate a PSK
+ if self.wpa_driver != 'ralink legacy': # Enhanced Ralink legacy drivers are handled later
+ if not self.network.get('key') == None:
+ self.SetStatus('generating_psk')
+
+ print 'Generating psk...'
+ key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*', re.DOTALL | re.I | re.M | re.S)
+ self.network['psk'] = misc.RunRegex(key_pattern,
+ misc.Run('wpa_passphrase "' + self.network['essid'] + '" "' + self.network['key'] + '"'))
+ # Generate the wpa_supplicant file...
+ if not self.network.get('enctype') == None:
+ self.SetStatus('generating_wpa_config')
+ print 'Attempting to authenticate...'
+ wiface.Authenticate(self.network)
+
+ self.SetStatus('flushing_routing_table')
+ print 'Flushing the routing table...'
+ wiface.FlushRoutes()
+ liface.FlushRoutes()
+
+ self.SetStatus('configuring_interface')
+ print 'Configuring the wireless interface...'
+
+ # Bring up the network.
+ print 'Interface up...'
+ self.SetStatus('interface_up')
+ wiface.Up()
+
+ wiface.SetMode(self.network['mode'])
+ wiface.Associate(self.network['essid'],
+ self.network['channel'], self.network['bssid'])
+
+ # Authenticate after association for Ralink legacy cards.
+ if self.wpa_driver == 'ralink legacy':
+ if self.network.get('key') != None:
+ wiface.Authenticate(self.network)
+
+ if not self.network.get('broadcast') == None:
+ self.SetStatus('setting_broadcast_address')
+
+ print 'Setting the broadcast address...' + self.network['broadcast']
+ wiface.SetAddress(broadcast=self.network['broadcast'])
+
+ if not self.network.get('ip') == None:
+ self.SetStatus('setting_static_ip')
+ print 'Setting static IP : ' + self.network['ip']
+ wiface.SetAddress(self.network['ip'], self.network['netmask'])
+ print 'Setting default gateway : ' + self.network['gateway']
+ wiface.SetDefaultRoute(self.network['gateway'])
+ else:
+ # Run dhcp...
+ self.SetStatus('running_dhcp')
+ print "Running DHCP"
+ if not self.should_die:
+ wiface.StartDHCP()
+
+ if ((self.network.get('dns1') or self.network.get('dns2') or
+ self.network.get('dns3')) and
+ self.network.get('use_static_dns')):
+ self.SetStatus('setting_static_dns')
+ if self.network.get('use_global_dns'):
+ wnettools.SetDNS(misc.Noneify(self.global_dns_1),
+ misc.Noneify(self.global_dns_2),
+ misc.Noneify(self.global_dns_3))
+ else:
+ wnettools.SetDNS(self.network.get('dns1'),
+ self.network.get('dns2'), self.network.get('dns3'))
+
+ #execute post-connection script if necessary
+ if misc.Noneify(self.after_script):
+ print 'executing post connection script'
+ print misc.Run('./run-script.py ' + self.after_script)
+
+ self.SetStatus('done')
+ print 'Connecting thread exiting.'
+ self.is_connecting = False
+
+
+
+class Wired(Controller):
+ """ A wrapper for common wired interface functions. """
def CheckPluggedIn(self):
- mii_tool_data = misc.Run( 'mii-tool ' + self.wired_interface,True)
- if not misc.RunRegex(re.compile('(Invalid argument)',re.DOTALL | re.I |
- re.M | re.S),mii_tool_data) is None:
- print 'wired interface appears down, putting up for mii-tool check'
- misc.Run( 'ifconfig ' + self.wired_interface + ' up' )
- mii_tool_data = misc.Run( 'mii-tool ' + self.wired_interface)
- if not misc.RunRegex(re.compile('(link ok)',re.DOTALL | re.I | re.M |
- re.S),mii_tool_data) is None:
- return True
- else:
- return False
- # End function CheckPluggedIn
+ """ Check whether the wired connection is plugged in.
- def Connect(self,network):
- # Call the thread, so we don't hang up the entire works
- self.ConnectingThread = self.ConnectThread(network,
- self.wireless_interface,
- self.wired_interface,
- self.before_script,
- self.after_script,
- self.disconnect_script)
- self.ConnectingThread.start()
+ Returns:
+ The status of the physical connection link.
+
+ """
+ liface = wnettools.WiredInterface(self.wired_interface)
+ return liface.GetPluggedIn()
+
+
+ def Connect(self, network):
+ """ Spawn a connection thread to connect to the network.
+
+ Keyword arguments:
+ network -- network to connect to
+
+ """
+ self.connecting_thread = WiredConnectThread(network,
+ self.wireless_interface, self.wired_interface,
+ self.before_script, self.after_script,
+ self.disconnect_script, self.global_dns_1,
+ self.global_dns_2, self.global_dns_3)
+ self.connecting_thread.start()
return True
- # End function Connect
- class ConnectThread(threading.Thread):
- # Wired interface connect thread
- lock = thread.allocate_lock()
- ConnectingMessage = None
- ShouldDie = False
- def __init__(self,network,wireless,wired,before_script,after_script,
- disconnect_script):
- threading.Thread.__init__(self)
- self.network = network
- self.wireless_interface = wireless
- self.wired_interface = wired
- self.IsConnecting = False
- self.before_script = before_script
- self.after_script = after_script
- self.disconnect_script = disconnect_script
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'interface_down'
- finally:
- self.lock.release()
- # End function __init__
+ def GetIP(self):
+ """ Get the IP of the interface.
- def GetStatus(self):
- self.lock.acquire()
- try:
- print " ...lock acquired..."
- message = self.ConnectingMessage
- finally:
- self.lock.release()
- print " ...lock released..."
- return message
+ Returns:
+ The IP address of the interface in dotted notation.
- def run(self):
- # We don't touch the wifi interface
- # but we do remove all wifi entries from the
- # routing table.
- self.IsConnecting = True
- network = self.network
+ """
+ liface = wnettools.WiredInterface(self.wired_interface)
+ return liface.GetIP()
- if self.before_script != '' and self.before_script != None:
- print 'executing pre-connection script'
- misc.Run('./run-script.py ' + self.before_script)
-
- # Put it down
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'interface_down'
- finally:
- self.lock.release()
- print "interface down...", self.wired_interface
- misc.Run("ifconfig " + self.wired_interface + " down")
-
- # Set a false ip so that when we set the real one, the correct
- # routing entry is created
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'resetting_ip_address'
- finally:
- self.lock.release()
- print "setting false ip... 0.0.0.0 on", self.wired_interface
- misc.Run("ifconfig " + self.wired_interface + " 0.0.0.0")
- misc.Run("ifconfig " + self.wireless_interface + " 0.0.0.0")
-
- # Bring it up
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'interface_up'
- finally:
- self.lock.release()
- print "interface up...", self.wired_interface
- misc.Run("ifconfig " + self.wired_interface + " up")
-
- print "killing wpa_supplicant, dhclient, dhclient3"
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'removing_old_connection'
- finally:
- self.lock.release()
- misc.Run("killall dhclient dhclient3 wpa_supplicant")
-
- print "flushing the routing table..."
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'flushing_routing_table'
- finally:
- self.lock.release()
- misc.Run("ip route flush dev " + self.wireless_interface)
- misc.Run("ip route flush dev " + self.wired_interface)
-
- if not network.get("broadcast") is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_broadcast_address'
- finally:
- self.lock.release()
- print "setting the broadcast address..." + network["broadcast"]
- misc.Run("ifconfig " + self.wired_interface + " broadcast " +
- network["broadcast"])
-
- if not network.get("dns1") is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_static_dns'
- finally:
- self.lock.release()
- print "setting the first dns server...", network["dns1"]
- resolv = open("/etc/resolv.conf","w")
- misc.WriteLine(resolv,"nameserver " + network["dns1"])
- if not network.get("dns2") is None:
- print "setting the second dns server...", network["dns2"]
- misc.WriteLine(resolv,"nameserver " + network["dns2"])
- if not network.get("dns3") is None:
- print "setting the third dns server..."
- misc.WriteLine(resolv,"nameserver " + network["dns3"])
-
- if not network.get("ip") is None:
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'setting_static_ip'
- finally:
- self.lock.release()
- print "setting static ips...", network["ip"]
- misc.Run("ifconfig " + self.wired_interface + " " +
- network["ip"])
- misc.Run("ifconfig " + self.wired_interface + " netmask " +
- network["netmask"])
- print "adding default gateway..." + network["gateway"]
- misc.Run("route add default gw " + network["gateway"])
- else:
- # Run dhcp...
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'running_dhcp'
- finally:
- self.lock.release()
- print "running dhcp..."
- if not self.ShouldDie:
- misc.Run("dhclient " + self.wired_interface)
-
- self.lock.acquire()
- try:
- self.ConnectingMessage = 'done'
- finally:
- self.lock.release()
- self.IsConnecting = False
-
- if self.after_script != '' and self.after_script != None:
- print 'executing post connection script'
- misc.Run('./run-script.py ' + self.after_script)
- # End function run
def Disconnect(self):
- print 'wired disconnect running'
+ """ Disconnect from the network. """
+ liface = wnettools.WirelessInterface(self.wired_interface)
if self.disconnect_script != None:
- print 'running wired network disconnect script'
+ print 'Running wired disconnect script'
misc.Run(self.disconnect_script)
- misc.Run('ifconfig ' + self.wired_interface + ' 0.0.0.0')
- misc.Run('ifconfig ' + self.wired_interface + ' down')
+
+ liface.SetAddress('0.0.0.0')
+ liface.Down()
+
+
+
+class WiredConnectThread(ConnectThread):
+ """ A thread class to perform the connection to a wired network.
+
+ This thread, when run, will perform the necessary steps to connect
+ to the specified network.
+
+ """
+
+
+ def __init__(self, network, wireless, wired,
+ before_script, after_script, disconnect_script, gdns1,
+ gdns2, gdns3):
+ """ Initialise the thread with network information.
+
+ Keyword arguments:
+ network -- the network to connect to
+ wireless -- name of the wireless interface
+ wired -- name of the wired interface
+ before_script -- script to run before bringing up the interface
+ after_script -- script to run after bringing up the interface
+ disconnect_script -- script to run after disconnection
+ gdns1 -- global DNS server 1
+ gdns2 -- global DNS server 2
+ gdns3 -- global DNS server 3
+
+ """
+ ConnectThread.__init__(self, network, wireless, wired,
+ before_script, after_script, disconnect_script, gdns1,
+ gdns3, gdns3)
+
+
+ def run(self):
+ """ The main function of the connection thread.
+
+ This function performs the necessary calls to connect to the
+ specified network, using the information provided. The following
+ indicates the steps taken.
+ 1. Run pre-connection script.
+ 2. Take down the interface and clean up any previous
+ connections.
+ 3. Bring up the interface.
+ 4. Get/set IP address and DNS servers.
+
+ """
+ wiface = wnettools.WirelessInterface(self.wireless_interface)
+ liface = wnettools.WiredInterface(self.wired_interface)
+
+ self.is_connecting = True
+
+ # Execute pre-connection script if necessary
+ if self.before_script != '' and self.before_script != None:
+ print 'Executing pre-connection script'
+ print misc.Run('run-script.py ' + self.before_script)
+
+ # Put it down
+ print 'Interface down'
+ self.SetStatus('interface_down')
+ liface.Down()
+
+ # Set a false ip so that when we set the real one, the correct
+ # routing entry is created
+ print 'Setting false IP...'
+ self.SetStatus('resetting_ip_address')
+ wiface.SetAddress('0.0.0.0')
+ liface.SetAddress('0.0.0.0')
+
+ print 'Stopping wpa_supplicant, dhclient, dhclient3'
+ wiface.StopDHCP()
+ wiface.StopWPA()
+ liface.StopDHCP()
+
+ self.SetStatus('flushing_routing_table')
+ print 'Flushing the routing table...'
+ wiface.FlushRoutes()
+ liface.FlushRoutes()
+
+ # Bring up the network.
+ print 'Interface up...'
+ self.SetStatus('interface_up')
+ liface.Up()
+
+ if not self.network.get('broadcast') == None:
+ self.SetStatus('setting_broadcast_address')
+ print 'Setting the broadcast address...' + self.network['broadcast']
+ liface.SetAddress(broadcast=self.network['broadcast'])
+
+ if self.network.get('ip'):
+ self.SetStatus('setting_static_ip')
+ print 'Setting static IP : ' + self.network['ip']
+ liface.SetAddress(self.network['ip'], self.network['netmask'])
+ print 'Setting default gateway : ' + self.network['gateway']
+ liface.SetDefaultRoute(self.network['gateway'])
+ else:
+ # Run dhcp...
+ self.SetStatus('running_dhcp')
+ print "Running DHCP"
+ if not self.should_die:
+ liface.StartDHCP()
+
+ if ((self.network.get('dns1') or self.network.get('dns2') or
+ self.network.get('dns3')) and
+ self.network.get('use_static_dns')):
+ self.SetStatus('setting_static_dns')
+ if self.network.get('use_global_dns'):
+ wnettools.SetDNS(misc.Noneify(self.global_dns_1),
+ misc.Noneify(self.global_dns_2),
+ misc.Noneify(self.global_dns_3))
+ else:
+ wnettools.SetDNS(self.network.get('dns1'),
+ self.network.get('dns2'), self.network.get('dns3'))
+
+ #execute post-connection script if necessary
+ if misc.Noneify(self.after_script):
+ print 'executing post connection script'
+ print misc.Run('./run-script.py ' + self.after_script)
+
+ self.SetStatus('done')
+ print 'Connecting thread exiting.'
+ self.is_connecting = False
diff --git a/wnettools.py b/wnettools.py
new file mode 100644
index 0000000..fa73c2c
--- /dev/null
+++ b/wnettools.py
@@ -0,0 +1,555 @@
+#!/usr/bin/env python
+""" Network interface control tools for wicd.
+
+This module implements functions to control and obtain information from
+network interfaces.
+
+def SetDNS() -- Set the DNS servers of the system.
+def GetWirelessInterfaces() -- Get the wireless interfaces available.
+class Interface() -- Control a network interface.
+class WiredInterface() -- Control a wired network interface.
+class WirelessInterface() -- Control a wireless network interface.
+
+"""
+
+#
+# Copyright (C) 2007 Adam Blackburn
+# Copyright (C) 2007 Dan O'Reilly
+# Copyright (C) 2007 Byron Hillis
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License Version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+#
+
+import misc
+import re
+import wpath
+
+# Compile the regex patterns that will be used to search the output of iwlist scan for info
+# these are well tested, should work on most cards
+essid_pattern = re.compile('.*ESSID:"(.*?)"\n', re.DOTALL | re.I | re.M | re.S)
+ap_mac_pattern = re.compile('.*Address: (.*?)\n',re.DOTALL | re.I | re.M | re.S)
+channel_pattern = re.compile('.*Channel:? ?(\d\d?)',re.DOTALL | re.I | re.M | re.S)
+strength_pattern = re.compile('.*Quality:?=? ?(\d\d*)',re.DOTALL | re.I | re.M | re.S)
+altstrength_pattern = re.compile('.*Signal level:?=? ?(\d\d*)',re.DOTALL | re.I | re.M | re.S)
+mode_pattern = re.compile('.*Mode:(.*?)\n',re.DOTALL | re.I | re.M | re.S)
+freq_pattern = re.compile('.*Frequency:(.*?)\n',re.DOTALL | re.I | re.M | re.S)
+ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',re.S)
+
+wep_pattern = re.compile('.*Encryption key:(.*?)\n',re.DOTALL | re.I | re.M | re.S)
+altwpa_pattern = re.compile('(wpa_ie)',re.DOTALL | re.I | re.M | re.S)
+wpa1_pattern = re.compile('(WPA Version 1)',re.DOTALL | re.I | re.M | re.S)
+wpa2_pattern = re.compile('(WPA2)',re.DOTALL | re.I | re.M | re.S)
+
+
+def SetDNS(dns1=None, dns2=None, dns3=None):
+ """ Set the DNS of the system to the specified DNS servers.
+
+ Opens up resolv.conf and writes in the nameservers.
+
+ Keyword arguments:
+ dns1 -- IP address of DNS server 1
+ dns2 -- IP address of DNS server 1
+ dns3 -- IP address of DNS server 1
+
+ """
+ dns_ips = [dns1, dns2, dns3]
+
+ resolv = open("/etc/resolv.conf","w")
+ for dns in dns_ips:
+ if dns:
+ print 'Setting DNS : ' + dns
+ resolv.write('nameserver ' + dns + '\n')
+ resolv.close()
+
+
+def GetWirelessInterfaces():
+ """ Get available wireless interfaces.
+
+ Returns:
+ The first interface available.
+
+ """
+ return misc.RunRegex(
+ re.compile('(\w*)\s*\w*\s*[a-zA-Z0-9.-_]*\s*(?=ESSID)', re.DOTALL | re.I | re.M | re.S),
+ misc.Run('iwconfig'))
+
+
+class Interface(object):
+ """ Control a network interface. """
+ def __init__(self, iface, verbose=True):
+ """ Initialise the object.
+
+ Keyword arguments:
+ iface -- the name of the interface
+ verbose -- whether to print every command run
+
+ """
+ self.iface = iface
+ self.verbose = verbose
+
+ def Check(self):
+ """ Check that all required tools are available."""
+ # TODO: Implement this function.
+ pass
+
+
+ def Up(self):
+ """ Bring the network interface up. """
+ cmd = 'ifconfig ' + self.iface + ' up'
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def Down(self):
+ """ Take down the network interface. """
+ cmd = 'ifconfig ' + self.iface + ' down'
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def SetAddress(self, ip=None, netmask=None, broadcast=None):
+ """ Set the IP addresses of an interface.
+
+ Keyword arguments:
+ ip -- interface IP address in dotted quad form
+ netmask -- netmask address in dotted quad form
+ broadcast -- broadcast address in dotted quad form
+
+ """
+ cmd = 'ifconfig ' + self.iface + ' '
+ if ip:
+ cmd += ip + ' '
+ if netmask:
+ cmd += 'netmask ' + netmask + ' '
+ if broadcast:
+ cmd += 'broadcast ' + broadcast + ' '
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def StartDHCP(self):
+ """ Start the DHCP client to obtain an IP address. """
+ cmd = 'dhclient ' + self.iface
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def StopDHCP(self):
+ """ Stop the DHCP client. """
+ cmd = 'killall dhclient dhclient3'
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def FlushRoutes(self):
+ """ Flush all network routes. """
+ cmd = 'ip route flush dev ' + self.iface
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def SetDefaultRoute(self, gw):
+ """ Add a default route with the specified gateway.
+
+ Keyword arguments:
+ gw -- gateway of the default route in dotted quad form
+
+ """
+ cmd = 'route add default gw ' + gw
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def GetIP(self):
+ """ Get the IP address of the interface.
+
+ Returns:
+ The IP address of the interface in dotted quad form.
+
+ """
+ cmd = 'ifconfig ' + self.iface
+ if self.verbose: print cmd
+ output = misc.Run(cmd)
+ return misc.RunRegex(ip_pattern,output)
+
+
+
+class WiredInterface(Interface):
+ """ Control a wired network interface. """
+ def __init__(self, iface, verbose=True):
+ """ Initialise the wired network interface class.
+
+ Keyword arguments:
+ iface -- name of the interface
+ verbose -- print all commands
+
+ """
+ Interface.__init__(self, iface, verbose)
+
+
+ def GetPluggedIn(self):
+ """ Get the current physical connection state. """
+ mii_tool_data = misc.Run( 'mii-tool ' + self.iface,True)
+ if not misc.RunRegex(re.compile('(Invalid argument)',re.DOTALL | re.I | re.M | re.S),mii_tool_data) == None:
+ print 'wired interface appears down, putting up for mii-tool check'
+ misc.Run( 'ifconfig ' + self.iface + ' up' )
+ mii_tool_data = misc.Run( 'mii-tool ' + self.iface)
+ if not misc.RunRegex(re.compile('(link ok)',re.DOTALL | re.I | re.M | re.S),mii_tool_data) == None:
+ return True
+ else:
+ return False
+
+
+
+class WirelessInterface(Interface):
+ """ Control a wireless network interface. """
+ def __init__(self, iface, verbose=True, wpa_driver='wext'):
+ """ Initialise the wireless network interface class.
+
+ Keyword arguments:
+ iface -- name of the interface
+ verbose -- print all commands
+
+ """
+ Interface.__init__(self, iface, verbose)
+ self.wpa_driver = wpa_driver
+
+
+ def SetEssid(self, essid):
+ """ Set the essid of the wireless interface.
+
+ Keyword arguments:
+ essid -- essid to set the interface to
+
+ """
+ cmd = 'iwconfig ' + self.wireless_interface + ' essid "' + essid + '"'
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def StopWPA(self):
+ """ Stop wireless encryption. """
+ cmd = 'killall wpa_supplicant'
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def GetNetworks(self):
+ """ Get a list of available wireless networks.
+
+ Returns:
+ A list containing available wireless networks.
+
+ """
+ cmd = 'iwlist ' + self.iface + ' scan'
+ if self.verbose: print cmd
+ results = misc.Run(cmd)
+
+ # Split the networks apart, using Cell as our split point
+ # this way we can look at only one network at a time
+ networks = results.split( ' Cell ' )
+
+ # An array for the access points
+ access_points = []
+ for cell in networks:
+ # Only use sections where there is an ESSID.
+ if cell.count('ESSID:') > 0:
+ # Add this network to the list of networks
+ access_points.append(self._ParseAccessPoint(cell))
+
+ return access_points
+
+
+ def _FreqToChannel(self, freq):
+ """ Translate the specified frequency to a channel.
+
+ Note: This function is simply a lookup table and therefore the
+ freq argument must be in the table to provide a valid channel.
+
+ Keyword arguments:
+ freq -- string containing the specified frequency
+
+ Returns:
+ The channel number, or None if not found.
+
+ """
+ if freq == '2.412 GHz': return 1
+ elif freq == '2.417 GHz': return 2
+ elif freq == '2.422 GHz': return 3
+ elif freq == '2.427 GHz': return 4
+ elif freq == '2.432 GHz': return 5
+ elif freq == '2.437 GHz': return 6
+ elif freq == '2.442 GHz': return 7
+ elif freq == '2.447 GHz': return 8
+ elif freq == '2.452 GHz': return 9
+ elif freq == '2.457 GHz': return 10
+ elif freq == '2.462 GHz': return 11
+ elif freq == '2.467 GHz': return 12
+ elif freq == '2.472 GHz': return 13
+ elif freq == '2.484 GHz': return 14
+ else:
+ print 'Couldn\'t determine channel number for current network - ' + freq
+ return None
+
+
+ def _ParseAccessPoint(self, cell):
+ """ Parse a single cell from the output of iwlist.
+
+ Keyword arguments:
+ cell -- string containing the cell information
+
+ Returns:
+ A dictionary containing the cell networks properties.
+
+ """
+ ap = {}
+
+ # ESSID - Switch '' to 'Hidden' to remove
+ # brackets that can mix up formatting.
+ ap['essid'] = misc.RunRegex(essid_pattern, cell)
+ if ap['essid'] == '':
+ ap['essid'] = 'Hidden'
+ ap['hidden'] = True
+ else:
+ ap['hidden'] = False
+
+ # Channel - For cards that don't have a channel number,
+ # convert the frequency.
+ ap['channel'] = misc.RunRegex(channel_pattern, cell)
+ if ap['channel'] == None:
+ freq = misc.RunRegex(freq_pattern, cell)
+ ap['channel'] = self._FreqToChannel(freq)
+
+ # BSSID
+ ap['bssid'] = misc.RunRegex(ap_mac_pattern, cell)
+
+ # Mode
+ ap['mode'] = misc.RunRegex(mode_pattern, cell)
+
+ # Encryption - Default to WEP
+ if misc.RunRegex(wep_pattern, cell) == 'on':
+ if self.wpa_driver != 'ralink legacy':
+ ap['encryption'] = True
+ ap['encryption_method'] = 'WEP'
+
+ if misc.RunRegex(wpa1_pattern,cell) == 'WPA Version 1':
+ ap['encryption_method'] = 'WPA'
+
+ if misc.RunRegex(altwpa_pattern,cell) == 'wpa_ie':
+ ap['encryption_method'] = 'WPA'
+
+ if misc.RunRegex(wpa2_pattern,cell) == 'WPA2':
+ ap['encryption_method'] = 'WPA2'
+
+ # Support for ralink legacy drivers (maybe only serialmonkey enhanced),
+ # may not work w/ hidden networks
+ else:
+ iwpriv = misc.Run('iwpriv ' + self.wireless_interface + ' get_site_survey')
+ lines = iwpriv.splitlines()
+ lines = lines[2:]
+ for x in lines: # Iterate through all networks found
+ info = x.split()
+ if len(info) < 5 or info == None or info == '': # Make sure we read in a valid entry
+ break;
+ if info[2] == ap['essid']:
+ ap['encryption'] = True
+ if info[5] == 'WEP' or (
+ (info[5] == 'OPEN' or info[5] == 'SHARED') and
+ info[4] == 'WEP'):
+ ap['encryption_method'] = 'WEP'
+ elif info[5] == 'WPA-PSK':
+ ap['encryption_method'] = 'WPA'
+ elif info[5] == 'WPA2-PSK':
+ ap['encryption_method'] = 'WPA2'
+ else:
+ print 'Unknown AuthMode, can\'t assign encryption_method!!'
+ ap['encryption_method'] = 'Unknown'
+
+ # Set signal strength here (in dBm, not %)
+ ap['quality'] = info[1][1:]
+ else:
+ ap['encryption'] = False
+
+ if self.wpa_driver != 'ralink legacy':
+ # Set strength to -1 if the quality is not found
+ if misc.RunRegex(strength_pattern,cell):
+ ap['quality'] = misc.RunRegex(strength_pattern,cell)
+ elif misc.RunRegex(altstrength_pattern,cell):
+ ap['quality'] = misc.RunRegex(altstrength_pattern,cell)
+ else:
+ ap['quality'] = -1
+
+ return ap
+
+
+ def SetMode(self, mode):
+ """ Set the mode of the wireless interface.
+
+ Keyword arguments:
+ mode -- mode to set the interface to
+
+ """
+ if mode.lower() == 'master':
+ mode = 'managed'
+ cmd = 'iwconfig ' + self.iface + ' mode ' + mode
+ if self.verbose: print cmd
+ results = misc.Run(cmd)
+
+
+ def SetChannel(self, channel):
+ """ Set the channel of the wireless interface.
+
+ Keyword arguments:
+ channel -- channel to set the interface to
+
+ """
+ cmd = 'iwconfig ' + self.iface + ' channel ' + str(channel)
+ if self.verbose: print cmd
+ results = misc.Run(cmd)
+
+
+ def SetKey(self, key):
+ """ Set the encryption key of the wireless interface.
+
+ Keyword arguments:
+ key -- encryption key to set
+
+ """
+ cmd = 'iwconfig ' + self.iface + ' key ' + key
+ if self.verbose: print cmd
+ results = misc.Run(cmd)
+
+
+ def Associate(self, essid, channel=None, bssid=None):
+ """ Associate with the specified wireless network.
+
+ Keyword arguments:
+ essid -- essid of the network
+ channel -- channel of the network
+ bssid -- bssid of the network
+
+ """
+ cmd = 'iwconfig ' + self.iface + ' essid "' + essid + '"'
+ if channel:
+ cmd += ' channel ' + str(channel)
+ if bssid:
+ cmd += ' ap ' + bssid
+ if self.verbose: print cmd
+ results = misc.Run(cmd)
+
+
+ def Authenticate(self, network):
+ """ Authenticate with the specified wireless network.
+
+ Keyword arguments:
+ network -- dictionary containing network info
+
+ """
+ misc.ParseEncryption(network)
+ if self.wpa_driver == 'ralink legacy':
+ _AuthenticateRalinkLegacy(network)
+ else:
+ cmd = ('wpa_supplicant -B -i ' + self.iface + ' -c "'
+ + wpath.networks + network['bssid'].replace(':','').lower()
+ + '" -D ' + self.wpa_driver)
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def _AuthenticateRalinkLegacy(self, network):
+ """ Authenticate with the specified wireless network.
+
+ This function handles Ralink legacy cards that cannot use
+ wpa_supplicant.
+
+ Keyword arguments:
+ network -- dictionary containing network info
+
+ """
+ if network.get('key') != None:
+ iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey')
+ lines = iwpriv.splitlines()
+ lines = lines[2:]
+ for x in lines:
+ info = x.split()
+ if len(info) < 5:
+ break
+ if info[2] == network.get('essid'):
+ if info[5] == 'WEP' or (info[5] == 'OPEN' and info[4] == 'WEP'): # Needs to be tested
+ print 'Setting up WEP'
+ cmd = 'iwconfig ' + self.iface + ' key ' + network.get('key')
+ if self.verbose: print cmd
+ misc.Run(cmd)
+ else:
+ if info[5] == 'SHARED' and info[4] == 'WEP':
+ print 'Setting up WEP'
+ auth_mode = 'SHARED'
+ key_name = 'Key1'
+ elif info[5] == 'WPA-PSK':
+ print 'Setting up WPA-PSK'
+ auth_mode = 'WPAPSK'
+ key_name = 'WPAPSK'
+ elif info[5] == 'WPA2-PSK':
+ print 'Setting up WPA2-PSK'
+ auth_mode = 'WPA2PSK'
+ key_name = 'WPAPSK'
+ else:
+ print 'Unknown AuthMode, can\'t complete connection process!'
+ return
+
+ cmd_list = []
+ cmd_list.append('NetworkType=' + info[6])
+ cmd_list.append('AuthMode=' + auth_mode)
+ cmd_list.append('EncryptType=' + info[4])
+ cmd_list.append('SSID=' + info[2])
+ cmd_list.append(key_name + '=' + network.get('key'))
+ if info[5] == 'SHARED' and info[4] == 'WEP':
+ cmd_list.append('DefaultKeyID=1')
+ #TODO: Confirm whether this second SSID set is required.
+ cmd_list.append('SSID=' + info[2])
+
+ for cmd in cmd_list:
+ cmd = 'iwpriv ' + self.iface + ' '
+ if self.verbose: print cmd
+ misc.Run(cmd)
+
+
+ def GetSignalStrength(self):
+ """ Get the signal strength of the current network.
+
+ Returns:
+ The signal strength.
+
+ """
+ cmd = 'iwconfig ' + self.iface
+ if self.verbose: print cmd
+ output = misc.Run(cmd)
+ strength = misc.RunRegex(strength_pattern,output)
+ if strength == None:
+ strength = misc.RunRegex(altstrength_pattern,output)
+
+ return strength
+
+
+ def GetCurrentNetwork(self):
+ """ Get the essid of the current network.
+
+ Returns:
+ The current network essid.
+
+ """
+ cmd = 'iwconfig ' + self.iface
+ if self.verbose: print cmd
+ output = misc.Run(cmd)
+ return misc.RunRegex(re.compile('.*ESSID:"(.*?)"',re.DOTALL | re.I | re.M | re.S), output)
+