1
0
mirror of https://github.com/gryf/wicd.git synced 2026-03-07 01:55:49 +01:00

2to3 transformation

This commit is contained in:
Guido Maria Serra
2019-08-12 17:00:19 +02:00
parent 49523ed2bd
commit 681beb13b1
27 changed files with 541 additions and 543 deletions

View File

@@ -35,9 +35,9 @@ try:
dbusmanager.connect_to_dbus()
daemon = dbusmanager.get_interface('daemon')
wireless = dbusmanager.get_interface('wireless')
except Exception, e:
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Could not connect to daemon.'
except Exception as e:
print("Exception caught: %s" % str(e), file=sys.stderr)
print('Could not connect to daemon.', file=sys.stderr)
sys.exit(1)
def handler(*args):
@@ -45,7 +45,7 @@ def handler(*args):
pass
def error_handler(*args):
""" Error handler. """
print >> sys.stderr, 'Async error autoconnecting.'
print('Async error autoconnecting.', file=sys.stderr)
sys.exit(3)
if __name__ == '__main__':
@@ -55,7 +55,7 @@ if __name__ == '__main__':
if not daemon.CheckIfConnecting():
daemon.AutoConnect(True, reply_handler=handler,
error_handler=error_handler)
except Exception, e:
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Error autoconnecting.'
except Exception as e:
print("Exception caught: %s" % str(e), file=sys.stderr)
print('Error autoconnecting.', file=sys.stderr)
sys.exit(2)

View File

@@ -31,7 +31,7 @@ import wicd.wpath as wpath
def fail(backend_name, reason):
""" Helper to warn the user about failure in loading backend. """
print "Failed to load backend %s: %s" % (backend_name, reason)
print("Failed to load backend %s: %s" % (backend_name, reason))
return True
@@ -80,7 +80,7 @@ class BackendManager(object):
def _load_backend(self, backend_name):
""" Imports a backend and returns the loaded module. """
print 'trying to load backend %s' % backend_name
print('trying to load backend %s' % backend_name)
backend_path = os.path.join(self.backend_dir,
'be-' + backend_name + '.py')
if self._valid_backend_file(backend_path):
@@ -124,5 +124,5 @@ class BackendManager(object):
return None
self.__loaded_backend = backend
print 'successfully loaded backend %s' % backend_name
print('successfully loaded backend %s' % backend_name)
return backend

View File

@@ -41,13 +41,13 @@ try:
import iwscan
IWSCAN_AVAIL = True
except ImportError:
print "WARNING: python-iwscan not found, falling back to using iwlist scan."
print("WARNING: python-iwscan not found, falling back to using iwlist scan.")
IWSCAN_AVAIL = False
try:
import wpactrl
WPACTRL_AVAIL = True
except ImportError:
print "WARNING: python-wpactrl not found, falling back to using wpa_cli."
print("WARNING: python-wpactrl not found, falling back to using wpa_cli.")
WPACTRL_AVAIL = False
import re
@@ -165,9 +165,9 @@ class Interface(BaseInterface):
data = (self.iface + '\0' * 16)[:18]
try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data)
except IOError, e:
except IOError as e:
if self.verbose:
print "SIOCGIFFLAGS failed: " + str(e)
print("SIOCGIFFLAGS failed: " + str(e))
return False
flags, = struct.unpack('H', result[16:18])
@@ -204,8 +204,8 @@ class WiredInterface(Interface, BaseWiredInterface):
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
return self._mii_get_plugged_in()
else:
print ('Error: No way of checking for a wired connection. Make' +
'sure that either mii-tool or ethtool is installed.')
print(('Error: No way of checking for a wired connection. Make' +
'sure that either mii-tool or ethtool is installed.'))
return False
def _eth_get_plugged_in(self):
@@ -224,9 +224,9 @@ class WiredInterface(Interface, BaseWiredInterface):
data = (self.iface + '\0' * 16)[:16] + arg
try:
fcntl.ioctl(self.sock.fileno(), SIOCETHTOOL, data)
except IOError, e:
except IOError as e:
if self.verbose:
print 'SIOCETHTOOL failed: ' + str(e)
print('SIOCETHTOOL failed: ' + str(e))
return False
return bool(buff.tolist()[1])
@@ -244,9 +244,9 @@ class WiredInterface(Interface, BaseWiredInterface):
0x0004, 0)
try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff)
except IOError, e:
except IOError as e:
if self.verbose:
print 'SIOCGMIIPHY failed: ' + str(e)
print('SIOCGMIIPHY failed: ' + str(e))
return False
reg = struct.unpack('16shhhh', result)[-1]
return bool(reg & 0x0004)
@@ -286,16 +286,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
if not self.scan_iface:
try:
self.scan_iface = iwscan.WirelessInterface(self.iface)
except iwscan.error, e:
print "GetNetworks caught an exception: %s" % e
except iwscan.error as e:
print("GetNetworks caught an exception: %s" % e)
return []
try:
results = self.scan_iface.Scan()
except iwscan.error, e:
print "ERROR: %s" % e
except iwscan.error as e:
print("ERROR: %s" % e)
return []
return filter(None, [self._parse_ap(cell) for cell in results])
return [_f for _f in [self._parse_ap(cell) for cell in results] if _f]
def _parse_ap(self, cell):
""" Parse a single cell from the python-iwscan list. """
@@ -303,7 +303,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
try:
ap['essid'] = misc.to_unicode(cell['essid'])
except UnicodeError:
print 'Unicode problem with the current network essid, ignoring!!'
print('Unicode problem with the current network essid, ignoring!!')
return None
if ap['essid'] in [ "", '<hidden>']:
@@ -356,12 +356,12 @@ class WirelessInterface(Interface, BaseWirelessInterface):
if os.path.exists(socket_loc):
try:
return wpactrl.WPACtrl(socket_loc)
except wpactrl.error, e:
print "Couldn't open ctrl_interface: %s" % e
except wpactrl.error as e:
print("Couldn't open ctrl_interface: %s" % e)
return None
else:
print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface
print("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface)
return None
def ValidateAuthentication(self, auth_time):
@@ -392,7 +392,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
wpa = self._connect_to_wpa_ctrl_iface()
if not wpa:
print "Failed to open ctrl interface"
print("Failed to open ctrl interface")
return False
MAX_TIME = 35
@@ -402,12 +402,12 @@ class WirelessInterface(Interface, BaseWirelessInterface):
try:
status = wpa.request("STATUS").split("\n")
except:
print "wpa_supplicant status query failed."
print("wpa_supplicant status query failed.")
return False
if self.verbose:
print 'wpa_supplicant ctrl_interface status query is %s' \
% str(status)
print('wpa_supplicant ctrl_interface status query is %s' \
% str(status))
try:
[result] = [l for l in status if l.startswith("wpa_state=")]
@@ -426,7 +426,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
disconnected_time = 0
time.sleep(1)
print 'wpa_supplicant authentication may have failed.'
print('wpa_supplicant authentication may have failed.')
return False
@neediface(False)
@@ -458,28 +458,28 @@ class WirelessInterface(Interface, BaseWirelessInterface):
if info[2] == network.get('essid'):
if info[5] == 'WEP' or (info[5] == 'OPEN' and \
info[4] == 'WEP'):
print 'Setting up WEP'
print('Setting up WEP')
cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')])
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
else:
if info[5] == 'SHARED' and info[4] == 'WEP':
print 'Setting up WEP'
print('Setting up WEP')
auth_mode = 'SHARED'
key_name = 'Key1'
elif info[5] == 'WPA-PSK':
print 'Setting up WPA-PSK'
print('Setting up WPA-PSK')
auth_mode = 'WPAPSK'
key_name = 'WPAPSK'
elif info[5] == 'WPA2-PSK':
print 'Setting up WPA2-PSK'
print('Setting up WPA2-PSK')
auth_mode = 'WPA2PSK'
key_name = 'WPAPSK'
else:
print 'Unknown AuthMode, can\'t complete ' + \
'connection process!'
print('Unknown AuthMode, can\'t complete ' + \
'connection process!')
return
cmd_list = []
@@ -495,7 +495,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
for cmd in cmd_list:
cmd = 'iwpriv ' + self.iface + ' '
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface("")
@@ -504,9 +504,9 @@ class WirelessInterface(Interface, BaseWirelessInterface):
data = (self.iface + '\0' * 32)[:32]
try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
except IOError, e:
except IOError as e:
if self.verbose:
print "SIOCGIWAP failed: " + str(e)
print("SIOCGIWAP failed: " + str(e))
return ""
raw_addr = struct.unpack("xxBBBBBB", result[:8])
return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr
@@ -519,9 +519,9 @@ class WirelessInterface(Interface, BaseWirelessInterface):
size = struct.calcsize(fmt)
try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRATE, data)[16:]
except IOError, e:
except IOError as e:
if self.verbose:
print "SIOCGIWRATE failed: " + str(e)
print("SIOCGIWRATE failed: " + str(e))
return ""
f, e, x, x = struct.unpack(fmt, result[:size])
return "%s %s" % ((f / 1000000), 'Mb/s')
@@ -562,9 +562,9 @@ class WirelessInterface(Interface, BaseWirelessInterface):
iwfreq = (self.iface + '\0' * 16)[:16] + arg
try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRANGE, iwfreq)
except IOError, e:
except IOError as e:
if self.verbose:
print "SIOCGIWRANGE failed: " + str(e)
print("SIOCGIWRANGE failed: " + str(e))
return None
# This defines the iwfreq struct, used to get signal strength.
fmt = "iiihb6ii4B4Bi32i2i2i2i2i3h8h2b2bhi8i2b3h2i2ihB17x" + 32 * "ihbb"

View File

@@ -27,7 +27,7 @@ reusable for other purposes as well.
import sys, os
from ConfigParser import RawConfigParser, ParsingError
from configparser import RawConfigParser, ParsingError
import codecs
from wicd.misc import Noneify, to_unicode
@@ -61,8 +61,8 @@ class ConfigManager(RawConfigParser):
self.write()
try:
self.read(path)
except ParsingError, p:
print "Could not start wicd: %s" % p.message
except ParsingError as p:
print("Could not start wicd: %s" % p.message)
sys.exit(1)
def __repr__(self):
@@ -86,7 +86,7 @@ class ConfigManager(RawConfigParser):
"""
if not self.has_section(section):
self.add_section(section)
if isinstance(value, basestring):
if isinstance(value, str):
value = to_unicode(value)
if value.startswith(' ') or value.endswith(' '):
value = "%(ws)s%(value)s%(ws)s" % {"value" : value,
@@ -115,7 +115,7 @@ class ConfigManager(RawConfigParser):
if self.has_option(section, option):
ret = RawConfigParser.get(self, section, option)
if (isinstance(ret, basestring) and ret.startswith(self.mrk_ws)
if (isinstance(ret, str) and ret.startswith(self.mrk_ws)
and ret.endswith(self.mrk_ws)):
ret = ret[3:-3]
ret = to_unicode(ret)
@@ -125,15 +125,15 @@ class ConfigManager(RawConfigParser):
if option in ['apsk', 'password', 'identity', \
'private_key', 'private_key_passwd', \
'key', 'passphrase']:
print ''.join(['found ', option, \
' in configuration *****'])
print(''.join(['found ', option, \
' in configuration *****']))
else:
print ''.join(['found ', option, ' in configuration ',
str(ret)])
print(''.join(['found ', option, ' in configuration ',
str(ret)]))
else: # Use the default, unless no default was provided
if default != "__None__":
print 'did not find %s in configuration, setting default %s' \
% (option, str(default))
print('did not find %s in configuration, setting default %s' \
% (option, str(default)))
self.set(section, option, str(default), write=True)
ret = default
else:
@@ -146,7 +146,7 @@ class ConfigManager(RawConfigParser):
except (ValueError, TypeError, AttributeError):
ret = Noneify(ret)
# This is a workaround for a python-dbus issue on 64-bit systems.
if isinstance(ret, (int, long)):
if isinstance(ret, int):
try:
Int32(ret)
except OverflowError:

View File

@@ -30,8 +30,8 @@ import string
import gobject
from threading import Thread
from subprocess import Popen, STDOUT, PIPE, call
from commands import getoutput
from itertools import repeat, chain, izip
from subprocess import getoutput
from itertools import repeat, chain
from pipes import quote
import socket
@@ -154,8 +154,8 @@ def Run(cmd, include_stderr=False, return_pipe=False,
try:
f = Popen(cmd, shell=False, stdout=PIPE, stdin=std_in, stderr=err,
close_fds=fds, cwd='/', env=tmpenv)
except OSError, e:
print "Running command %s failed: %s" % (str(cmd), str(e))
except OSError as e:
print("Running command %s failed: %s" % (str(cmd), str(e)))
return ""
if return_obj:
@@ -252,10 +252,10 @@ def ExecuteScript(script, verbose=False, extra_parameters=()):
# escape script name
script = quote(script)
if verbose:
print "Executing %s with params %s" % (script, params)
print("Executing %s with params %s" % (script, params))
ret = call('%s %s > /dev/null 2>&1' % (script, params), shell=True)
if verbose:
print "%s returned %s" % (script, ret)
print("%s returned %s" % (script, ret))
def ReadFile(filename):
""" read in a file and return it's contents as a string """
@@ -322,9 +322,9 @@ def ParseEncryption(network):
if rep_val:
line = line.replace("$_%s" % cur_val, str(rep_val))
else:
print "Ignoring template line: '%s'" % line
print("Ignoring template line: '%s'" % line)
else:
print "Weird parsing error occurred"
print("Weird parsing error occurred")
config_file = ''.join([config_file, line])
else: # Just a regular entry.
config_file = ''.join([config_file, line])
@@ -337,7 +337,7 @@ def ParseEncryption(network):
file_name = 'wired'
file_loc = os.path.join(wpath.networks, file_name)
f = open(file_loc, "w")
os.chmod(file_loc, 0600)
os.chmod(file_loc, 0o600)
os.chown(file_loc, 0, 0)
# We could do this above, but we'd like to read protect
# them before we write, so that it can't be read.
@@ -358,8 +358,8 @@ def LoadEncryptionMethods(wired = False):
active_fname = "active"
try:
enctypes = open(wpath.encryption + active_fname,"r").readlines()
except IOError, e:
print "Fatal Error: template index file is missing."
except IOError as e:
print("Fatal Error: template index file is missing.")
raise IOError(e)
# Parse each encryption method
@@ -391,7 +391,7 @@ def _parse_enc_template(enctype):
try:
f = open(os.path.join(wpath.encryption, enctype), "r")
except IOError:
print "Failed to open template file %s" % enctype
print("Failed to open template file %s" % enctype)
return None
cur_type = {}
@@ -408,7 +408,7 @@ def _parse_enc_template(enctype):
cur_type["required"] = __parse_field_ent(parse_ent(line, "require"))
if not cur_type["required"]:
# An error occured parsing the require line.
print "Invalid 'required' line found in template %s" % enctype
print("Invalid 'required' line found in template %s" % enctype)
continue
elif line.startswith("optional"):
cur_type["optional"] = __parse_field_ent(parse_ent(line,
@@ -416,7 +416,7 @@ def _parse_enc_template(enctype):
field_type="optional")
if not cur_type["optional"]:
# An error occured parsing the optional line.
print "Invalid 'optional' line found in template %s" % enctype
print("Invalid 'optional' line found in template %s" % enctype)
continue
elif line.startswith("protected"):
cur_type["protected"] = __parse_field_ent(
@@ -425,17 +425,17 @@ def _parse_enc_template(enctype):
)
if not cur_type["protected"]:
# An error occured parsing the protected line.
print "Invalid 'protected' line found in template %s" % enctype
print("Invalid 'protected' line found in template %s" % enctype)
continue
elif line.startswith("----"):
# We're done.
break
f.close()
if not cur_type["required"]:
print "Failed to find a 'require' line in template %s" % enctype
print("Failed to find a 'require' line in template %s" % enctype)
return None
if not cur_type["name"]:
print "Failed to find a 'name' line in template %s" % enctype
print("Failed to find a 'name' line in template %s" % enctype)
return None
else:
return cur_type
@@ -476,9 +476,9 @@ def sanitize_escaped(s):
def to_unicode(x):
""" Attempts to convert a string to utf-8. """
# If this is a unicode string, encode it and return
if not isinstance(x, basestring):
if not isinstance(x, str):
return x
if isinstance(x, unicode):
if isinstance(x, str):
return x.encode('utf-8')
x = sanitize_escaped(x)
@@ -500,7 +500,7 @@ def to_unicode(x):
def RenameProcess(new_name):
""" Renames the process calling the function to the given name. """
if 'linux' not in sys.platform:
print 'Unsupported platform'
print('Unsupported platform')
return False
try:
import ctypes
@@ -509,7 +509,7 @@ def RenameProcess(new_name):
libc.prctl(15, new_name, 0, 0, 0)
return True
except:
print "rename failed"
print("rename failed")
return False
def detect_desktop_environment():
@@ -639,7 +639,7 @@ def izip_longest(*args, **kwds):
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
for tup in izip(*iters):
for tup in zip(*iters):
yield tup
except IndexError:
pass
@@ -651,4 +651,4 @@ def grouper(n, iterable, fillvalue=None):
"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
return zip_longest(fillvalue=fillvalue, *args)

View File

@@ -55,8 +55,8 @@ def diewithdbus(func):
ret = func(self, *__args, **__kargs)
self.__lost_dbus_count = 0
return ret
except DBusException, e:
print "Caught exception %s" % str(e)
except DBusException as e:
print("Caught exception %s" % str(e))
if not hasattr(self, "__lost_dbus_count"):
self.__lost_dbus_count = 0
if self.__lost_dbus_count > 3:
@@ -188,7 +188,7 @@ class ConnectionStatus(object):
# If we haven't gotten any signal 4 runs in a row (12 seconds),
# try to reconnect.
self.connection_lost_counter += 1
print self.connection_lost_counter
print(self.connection_lost_counter)
if self.connection_lost_counter >= 4 and daemon.GetAutoReconnect():
wireless.DisconnectWireless()
self.connection_lost_counter = 0
@@ -218,7 +218,7 @@ class ConnectionStatus(object):
wifi_ip = None
if daemon.GetSuspend():
print "Suspended."
print("Suspended.")
state = misc.SUSPENDED
return self.update_state(state)
@@ -251,7 +251,7 @@ class ConnectionStatus(object):
# Don't trigger it if the gui is open, because autoconnect
# is disabled while it's open.
if not daemon.GetGUIOpen():
print 'Killing wireless connection to switch to wired...'
print('Killing wireless connection to switch to wired...')
wireless.DisconnectWireless()
daemon.AutoConnect(False, reply_handler=lambda *a:None,
error_handler=lambda *a:None)
@@ -291,7 +291,7 @@ class ConnectionStatus(object):
self.reconnect_tries = 0
info = [str(wired_ip)]
else:
print 'ERROR: Invalid state!'
print('ERROR: Invalid state!')
return True
daemon.SetConnectionStatus(state, info)
@@ -345,14 +345,14 @@ class ConnectionStatus(object):
# Some checks to keep reconnect retries from going crazy.
if (self.reconnect_tries > 3 and
(time.time() - self.last_reconnect_time) < 200):
print "Throttling autoreconnect"
print("Throttling autoreconnect")
return
self.reconnecting = True
daemon.SetCurrentInterface('')
if daemon.ShouldAutoReconnect():
print 'Starting automatic reconnect process'
print('Starting automatic reconnect process')
self.last_reconnect_time = time.time()
self.reconnect_tries += 1
@@ -362,10 +362,10 @@ class ConnectionStatus(object):
if from_wireless and cur_net_id > -1:
# make sure disconnect scripts are run
# before we reconnect
print 'Disconnecting from network'
print('Disconnecting from network')
wireless.DisconnectWireless()
print 'Trying to reconnect to last used wireless ' + \
'network'
print('Trying to reconnect to last used wireless ' + \
'network')
wireless.ConnectWireless(cur_net_id)
else:
daemon.AutoConnect(True, reply_handler=reply_handle,

View File

@@ -50,10 +50,10 @@ import os
from signal import SIGTERM
# wicd imports
import misc
from . import misc
import wpath
from backend import BackendManager
from translations import _
from .backend import BackendManager
from .translations import _
if __name__ == '__main__':
wpath.chdir(__file__)
@@ -123,9 +123,9 @@ def expand_script_macros(script, msg, bssid, essid):
"""
def repl(match):
macro = match.group(1).lower()
if macro_dict.has_key(macro):
if macro in macro_dict:
return macro_dict[macro]
print 'Warning: found illegal macro %s in %s script' % (macro, msg)
print('Warning: found illegal macro %s in %s script' % (macro, msg))
return match.group()
macro_dict = { 'script' : msg,
@@ -133,7 +133,7 @@ def expand_script_macros(script, msg, bssid, essid):
'essid' : essid }
regex = re.compile(r'%\{([a-zA-Z0-9]+)\}')
expanded = regex.sub(repl, script)
print "Expanded '%s' to '%s'" % (script, expanded)
print("Expanded '%s' to '%s'" % (script, expanded))
return expanded
@@ -223,7 +223,7 @@ class Controller(object):
misc.ExecuteScripts(wpath.predisconnectscripts, self.debug,
extra_parameters=(nettype, name, mac))
if self.pre_disconnect_script:
print 'Running pre-disconnect script'
print('Running pre-disconnect script')
misc.ExecuteScript(expand_script_macros(self.pre_disconnect_script,
'pre-disconnection',
mac, name),
@@ -237,7 +237,7 @@ class Controller(object):
misc.ExecuteScripts(wpath.postdisconnectscripts, self.debug,
extra_parameters=(nettype, name, mac))
if self.post_disconnect_script:
print 'Running post-disconnect script'
print('Running post-disconnect script')
misc.ExecuteScript(expand_script_macros(self.post_disconnect_script,
'post-disconnection',
mac, name),
@@ -249,7 +249,7 @@ class Controller(object):
def KillDHCP(self):
""" Kill the managed DHCP client if its in a connecting state. """
print 'running kill dhcp.'
print('running kill dhcp.')
if (self.connecting_thread.is_connecting and
self.iface.dhcp_object):
if self.iface.dhcp_object.poll() is None:
@@ -403,14 +403,14 @@ class ConnectThread(threading.Thread):
routing entry is created.
"""
print 'Setting false IP...'
print('Setting false IP...')
self.SetStatus('resetting_ip_address')
iface.SetAddress('0.0.0.0')
@abortable
def put_iface_down(self, iface):
""" Puts the given interface down. """
print 'Putting interface down'
print('Putting interface down')
self.SetStatus('interface_down')
iface.Down()
@@ -430,7 +430,7 @@ class ConnectThread(threading.Thread):
"""
if script:
print 'Executing %s script' % (msg)
print('Executing %s script' % (msg))
misc.ExecuteScript(expand_script_macros(script, msg, bssid, essid),
self.debug)
@@ -438,7 +438,7 @@ class ConnectThread(threading.Thread):
def flush_routes(self, iface):
""" Flush the routes for both wired/wireless interfaces. """
self.SetStatus('flushing_routing_table')
print 'Flushing the routing table...'
print('Flushing the routing table...')
iface.FlushRoutes()
@abortable
@@ -446,7 +446,7 @@ class ConnectThread(threading.Thread):
""" Set the broadcast address for the given interface. """
if not self.network.get('broadcast') == None:
self.SetStatus('setting_broadcast_address')
print 'Setting the broadcast address...' + self.network['broadcast']
print('Setting the broadcast address...' + self.network['broadcast'])
iface.SetAddress(broadcast=self.network['broadcast'])
@abortable
@@ -458,10 +458,10 @@ class ConnectThread(threading.Thread):
"""
if self.network.get('ip'):
self.SetStatus('setting_static_ip')
print 'Setting static IP : ' + self.network['ip']
print('Setting static IP : ' + self.network['ip'])
iface.SetAddress(self.network['ip'], self.network['netmask'])
if self.network.get('gateway'):
print 'Setting default gateway : ' + self.network['gateway']
print('Setting default gateway : ' + self.network['gateway'])
iface.SetDefaultRoute(self.network['gateway'])
else:
# Run dhcp...
@@ -472,10 +472,10 @@ class ConnectThread(threading.Thread):
self.network['dhcphostname'] = os.uname()[1]
if self.network['usedhcphostname']:
hname = self.network['dhcphostname']
print "Running DHCP with hostname", hname
print("Running DHCP with hostname", hname)
else:
hname = None
print "Running DHCP with NO hostname"
print("Running DHCP with NO hostname")
# Check if a global DNS is configured. If it is, then let the DHCP know *not* to update resolv.conf
staticdns = False
@@ -525,7 +525,7 @@ class ConnectThread(threading.Thread):
@abortable
def release_dhcp_clients(self, iface):
""" Release all running dhcp clients. """
print "Releasing DHCP leases..."
print("Releasing DHCP leases...")
iface.ReleaseDHCP()
def connect_aborted(self, reason):
@@ -536,7 +536,7 @@ class ConnectThread(threading.Thread):
self.is_aborted = True
self.connect_result = reason
self.is_connecting = False
print 'exiting connection thread'
print('exiting connection thread')
def abort_connection(self, reason=""):
""" Schedule a connection abortion for the given reason. """
@@ -556,13 +556,13 @@ class ConnectThread(threading.Thread):
@abortable
def stop_wpa(self, iface):
""" Stops wpa_supplicant. """
print 'Stopping wpa_supplicant'
print('Stopping wpa_supplicant')
iface.StopWPA()
@abortable
def put_iface_up(self, iface):
""" Bring up given interface. """
print 'Putting interface up...'
print('Putting interface up...')
self.SetStatus('interface_up')
iface.Up()
for x in range(0, 5):
@@ -572,7 +572,7 @@ class ConnectThread(threading.Thread):
self.abort_if_needed()
# If we get here, the interface never came up
print "WARNING: Timed out waiting for interface to come up"
print("WARNING: Timed out waiting for interface to come up")
class Wireless(Controller):
@@ -657,7 +657,7 @@ class Wireless(Controller):
# Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX"
essid = misc.Noneify(essid)
if essid is not None:
print 'Setting hidden essid ' + essid
print('Setting hidden essid ' + essid)
wiface.SetEssid(essid)
# sleep for a bit; scanning to fast will result in nothing
time.sleep(1)
@@ -792,23 +792,23 @@ class Wireless(Controller):
"""
wiface = self.wiface
print 'Creating ad-hoc network'
print 'Stopping dhcp client and wpa_supplicant'
print('Creating ad-hoc network')
print('Stopping dhcp client and wpa_supplicant')
wiface.ReleaseDHCP()
wiface.StopWPA()
print 'Putting wireless interface down'
print('Putting wireless interface down')
wiface.Down()
print 'Setting mode, channel, and essid'
print('Setting mode, channel, and essid')
wiface.SetMode('ad-hoc')
wiface.SetChannel(channel)
wiface.SetEssid(essid)
# Right now it just assumes you're using WEP
if enc_used:
print 'Setting encryption key'
print('Setting encryption key')
wiface.SetKey(key)
print 'Putting interface up'
print('Putting interface up')
wiface.Up()
print 'Setting IP address'
print('Setting IP address')
wiface.SetAddress(ip, '255.255.255.0')
def DetectWirelessInterface(self):
@@ -843,10 +843,10 @@ class Wireless(Controller):
action = 'block'
for t in types:
cmd = ['rfkill', action, t]
print "rfkill: %sing %s" % (action, t)
print("rfkill: %sing %s" % (action, t))
misc.Run(cmd)
return True
except Exception, e:
except Exception as e:
raise e
return False
@@ -858,9 +858,8 @@ class Wireless(Controller):
"""
cmd = 'rfkill list'
rfkill_out = misc.Run(cmd)
soft_blocks = filter(lambda x: x.startswith('Soft'),
rfkill_out.split('\t'))
for line in map(lambda x: x.strip(), soft_blocks):
soft_blocks = [x for x in rfkill_out.split('\t') if x.startswith('Soft')]
for line in [x.strip() for x in soft_blocks]:
if line.endswith('yes'):
return True
return False
@@ -983,7 +982,7 @@ class WirelessConnectThread(ConnectThread):
if self.network.get('enctype'):
self.SetStatus('validating_authentication')
if not wiface.ValidateAuthentication(time.time()):
print "connect result is %s" % self.connect_result
print("connect result is %s" % self.connect_result)
if not self.connect_result or self.connect_result == 'failed':
self.abort_connection('bad_pass')
@@ -1003,9 +1002,9 @@ class WirelessConnectThread(ConnectThread):
self.network['bssid'], self.network['essid'])
self.SetStatus('done')
print 'Connecting thread exiting.'
print('Connecting thread exiting.')
if self.debug:
print "IP Address is: " + str(wiface.GetIP())
print("IP Address is: " + str(wiface.GetIP()))
self.connect_result = "success"
self.is_connecting = False
@@ -1020,17 +1019,17 @@ class WirelessConnectThread(ConnectThread):
"""
if self.network.get('gateway') and self.should_verify_ap:
self.SetStatus('verifying_association')
print "Verifying AP association..."
print("Verifying AP association...")
for tries in range(1, 11):
print "Attempt %d of 10..." % tries
print("Attempt %d of 10..." % tries)
retcode = self.iface.VerifyAPAssociation(self.network['gateway'])
if retcode == 0:
print "Successfully associated."
print("Successfully associated.")
break
time.sleep(1)
#TODO this should be in wnettools.py
if retcode:
print "Connection Failed: Failed to ping the access point!"
print("Connection Failed: Failed to ping the access point!")
# Clean up before aborting.
iface.SetAddress('0.0.0.0')
iface.FlushRoutes()
@@ -1039,7 +1038,7 @@ class WirelessConnectThread(ConnectThread):
iface.StopWPA()
self.abort_connection('association_failed')
else:
print 'not verifying'
print('not verifying')
@abortable
def generate_psk_and_authenticate(self, wiface):
@@ -1052,22 +1051,22 @@ class WirelessConnectThread(ConnectThread):
# Check to see if we need to generate a PSK (only for non-ralink
# cards).
if self.debug:
print "enctype is %s" % self.network.get('enctype')
print("enctype is %s" % self.network.get('enctype'))
if self.network.get('key') and \
'wpa' in str(self.network.get('enctype')):
self.SetStatus('generating_psk')
print 'Generating psk...'
print('Generating psk...')
self.network['psk'] = wiface.GeneratePSK(self.network)
if not self.network.get('psk'):
self.network['psk'] = self.network['key']
print 'WARNING: PSK generation failed! Falling back to ' + \
print('WARNING: PSK generation failed! Falling back to ' + \
'wireless key.\nPlease report this error to the wicd ' + \
'developers!'
'developers!')
# Generate the wpa_supplicant file...
if self.network.get('enctype'):
self.SetStatus('generating_wpa_config')
print 'Attempting to authenticate...'
print('Attempting to authenticate...')
wiface.Authenticate(self.network)
@@ -1248,9 +1247,9 @@ class WiredConnectThread(ConnectThread):
'wired')
self.SetStatus('done')
print 'Connecting thread exiting.'
print('Connecting thread exiting.')
if self.debug:
print "IP Address is: " + str(liface.GetIP())
print("IP Address is: " + str(liface.GetIP()))
self.connect_result = "success"
self.is_connecting = False

View File

@@ -32,9 +32,9 @@ try:
bus = dbus.SystemBus()
proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
except Exception, e:
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Could not connect to daemon.'
except Exception as e:
print("Exception caught: %s" % str(e), file=sys.stderr)
print('Could not connect to daemon.', file=sys.stderr)
sys.exit(1)
@@ -43,7 +43,7 @@ if __name__ == '__main__':
daemon.Disconnect()
daemon.SetForcedDisconnect(False)
daemon.SetSuspend(True)
except Exception, e:
print >> sys.stderr, "Exception caught: %s" % str(e)
print >> sys.stderr, 'Error setting suspend.'
except Exception as e:
print("Exception caught: %s" % str(e), file=sys.stderr)
print('Error setting suspend.', file=sys.stderr)
sys.exit(2)

View File

@@ -44,9 +44,9 @@ def get_gettext():
lc, encoding = locale.getdefaultlocale(envvars=('LC_MESSAGES',
'LC_ALL', 'LANG',
'LANGUAGE'))
except ValueError, e:
print str(e)
print "Default locale unavailable, falling back to en_US"
except ValueError as e:
print(str(e))
print("Default locale unavailable, falling back to en_US")
if (lc):
langs += [lc]
langs += ["en_US"]

View File

@@ -133,7 +133,7 @@ class WicdDaemon(dbus.service.Object, object):
# Scan since we just got started
if not auto_connect:
print "--no-autoconnect detected, not autoconnecting..."
print("--no-autoconnect detected, not autoconnecting...")
self.SetForcedDisconnect(True)
self.wireless_bus.Scan()
@@ -161,7 +161,7 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.method('org.wicd.daemon')
def SetWiredInterface(self, interface):
""" Sets the wired interface for the daemon to use. """
print "setting wired interface %s" % (str(interface))
print("setting wired interface %s" % (str(interface)))
# Set it to a blank string, otherwise a network card named "None" will be searched
self.wired.wired_interface = noneToBlankString(interface)
self.config.set("Settings", "wired_interface", interface, write=True)
@@ -169,7 +169,7 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.method('org.wicd.daemon')
def SetWirelessInterface(self, interface):
""" Sets the wireless interface the daemon will use. """
print "setting wireless interface %s" % (str(interface))
print("setting wireless interface %s" % (str(interface)))
# Set it to a blank string, otherwise a network card named "None" will be searched
self.wifi.wireless_interface = noneToBlankString(interface)
self.config.set("Settings", "wireless_interface", interface, write=True)
@@ -177,14 +177,14 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.method('org.wicd.daemon')
def SetWPADriver(self, driver):
""" Sets the wpa driver the wpa_supplicant will use. """
print "setting wpa driver", str(driver)
print("setting wpa driver", str(driver))
self.wifi.wpa_driver = driver
self.config.set("Settings", "wpa_driver", driver, write=True)
@dbus.service.method('org.wicd.daemon')
def SetUseGlobalDNS(self, use):
""" Sets a boolean which determines if global DNS is enabled. """
print 'setting use global dns to', use
print('setting use global dns to', use)
use = misc.to_bool(use)
self.config.set("Settings", "use_global_dns", use, write=True)
self.use_global_dns = use
@@ -195,7 +195,7 @@ class WicdDaemon(dbus.service.Object, object):
def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None,
dns_dom =None, search_dom=None):
""" Sets the global dns addresses. """
print "setting global dns"
print("setting global dns")
self.config.set("Settings", "global_dns_1", misc.noneToString(dns1))
self.dns1 = dns1
self.wifi.global_dns_1 = dns1
@@ -218,26 +218,26 @@ class WicdDaemon(dbus.service.Object, object):
self.search_dom = search_dom
self.wifi.global_search_dom = search_dom
self.wired.global_search_dom = search_dom
print 'global dns servers are', dns1, dns2, dns3
print 'domain is %s' % dns_dom
print 'search domain is %s' % search_dom
print('global dns servers are', dns1, dns2, dns3)
print('domain is %s' % dns_dom)
print('search domain is %s' % search_dom)
self.config.write()
@dbus.service.method('org.wicd.daemon')
def SetBackend(self, backend):
""" Sets a new backend. """
print "setting backend to %s" % backend
print("setting backend to %s" % backend)
backends = networking.BACKEND_MGR.get_available_backends()
if backend not in backends:
print "backend %s not available, trying to fallback to another" \
% backend
print("backend %s not available, trying to fallback to another" \
% backend)
try:
backend = backends[0]
except IndexError:
print "ERROR: no backends available!"
print("ERROR: no backends available!")
return
else:
print "Fell back to backend %s" % backend
print("Fell back to backend %s" % backend)
self.config.set("Settings", "backend", backend, write=True)
if backend != self.GetCurrentBackend():
self.suspended = True
@@ -364,18 +364,18 @@ class WicdDaemon(dbus.service.Object, object):
fails it tries a wireless connection.
"""
print "Autoconnecting..."
print("Autoconnecting...")
if self.CheckIfConnecting():
if self.debug_mode:
print 'Already connecting, doing nothing.'
print('Already connecting, doing nothing.')
return
if self.wired_bus.CheckPluggedIn():
if self.debug_mode:
print "Starting wired autoconnect..."
print("Starting wired autoconnect...")
self._wired_autoconnect(fresh)
else:
if self.debug_mode:
print "Starting wireless autoconnect..."
print("Starting wireless autoconnect...")
self.wireless_bus._wireless_autoconnect(fresh)
@dbus.service.method('org.wicd.daemon')
@@ -392,7 +392,7 @@ class WicdDaemon(dbus.service.Object, object):
and wait for the user to initiate reconnection.
"""
print 'setting automatically reconnect when connection drops %s' % value
print('setting automatically reconnect when connection drops %s' % value)
self.config.set("Settings", "auto_reconnect", misc.to_bool(value),
write=True)
self.auto_reconnect = misc.to_bool(value)
@@ -416,7 +416,7 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.method('org.wicd.daemon')
def CancelConnect(self):
""" Cancels the wireless connection attempt """
print 'canceling connection attempt'
print('canceling connection attempt')
if self.wifi.connecting_thread:
self.wifi.connecting_thread.should_die = True
self.wifi.ReleaseDHCP()
@@ -478,7 +478,7 @@ class WicdDaemon(dbus.service.Object, object):
"""
if self.debug_mode and value:
print "Forced disconnect on"
print("Forced disconnect on")
self.forced_disconnect = bool(value)
@dbus.service.method('org.wicd.daemon')
@@ -666,7 +666,7 @@ class WicdDaemon(dbus.service.Object, object):
See misc.py for a definition of the constants.
"""
print "Setting dhcp client to %i" % (int(client))
print("Setting dhcp client to %i" % (int(client)))
self.dhcp_client = int(client)
self.wifi.dhcp_client = int(client)
self.wired.dhcp_client = int(client)
@@ -730,7 +730,7 @@ class WicdDaemon(dbus.service.Object, object):
# attempt to smartly connect to a wired network
# by using various wireless networks detected
# and by using plugged in USB devices
print self.LastScan
print(self.LastScan)
if self.GetWiredAutoConnectMethod() == 2 and \
not self.GetNeedWiredProfileChooser():
self.LaunchChooser()
@@ -740,8 +740,8 @@ class WicdDaemon(dbus.service.Object, object):
elif self.GetWiredAutoConnectMethod() == 1:
network = wiredb.GetDefaultWiredNetwork()
if not network:
print "Couldn't find a default wired connection," + \
" wired autoconnect failed."
print("Couldn't find a default wired connection," + \
" wired autoconnect failed.")
self.wireless_bus._wireless_autoconnect(fresh)
return
@@ -749,14 +749,14 @@ class WicdDaemon(dbus.service.Object, object):
else:
network = wiredb.GetLastUsedWiredNetwork()
if not network:
print "no previous wired profile available, wired " + \
"autoconnect failed."
print("no previous wired profile available, wired " + \
"autoconnect failed.")
self.wireless_bus._wireless_autoconnect(fresh)
return
wiredb.ReadWiredNetworkProfile(network)
wiredb.ConnectWired()
print "Attempting to autoconnect with wired interface..."
print("Attempting to autoconnect with wired interface...")
self.auto_connecting = True
time.sleep(1.5)
try:
@@ -818,7 +818,7 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s')
def ConnectResultsSent(self, result):
""" Signal emit when connection results are sent. """
print "Sending connection attempt result %s" % result
print("Sending connection attempt result %s" % result)
@dbus.service.method("org.wicd.daemon")
@dbus.service.signal(dbus_interface="org.wicd.daemon", signature='')
@@ -828,7 +828,7 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.signal(dbus_interface='org.wicd.daemon', signature='')
def LaunchChooser(self):
""" Emits the wired profile chooser dbus signal. """
print 'calling wired profile chooser'
print('calling wired profile chooser')
self.SetNeedWiredProfileChooser(True)
@dbus.service.signal(dbus_interface="org.wicd.daemon", signature='')
@@ -926,38 +926,38 @@ class WicdDaemon(dbus.service.Object, object):
app_conf.write()
if os.path.isfile(wireless_conf):
print "Wireless configuration file found..."
print("Wireless configuration file found...")
else:
print "Wireless configuration file not found, creating..."
print("Wireless configuration file not found, creating...")
open(wireless_conf, "w").close()
if os.path.isfile(wired_conf):
print "Wired configuration file found..."
print("Wired configuration file found...")
else:
print "Wired configuration file not found, creating a default..."
print("Wired configuration file not found, creating a default...")
# Create the file and a default profile
open(wired_conf, "w").close()
b_wired.CreateWiredNetworkProfile("wired-default", default=True)
if not os.path.isfile(dhclient_conf):
print "dhclient.conf.template not found, copying..."
print("dhclient.conf.template not found, copying...")
shutil.copy(dhclient_conf + ".default", dhclient_conf)
# Hide the files, so the keys aren't exposed.
print "chmoding configuration files 0600..."
os.chmod(app_conf.get_config(), 0600)
os.chmod(wireless_conf, 0600)
os.chmod(wired_conf, 0600)
os.chmod(dhclient_conf, 0644)
print("chmoding configuration files 0600...")
os.chmod(app_conf.get_config(), 0o600)
os.chmod(wireless_conf, 0o600)
os.chmod(wired_conf, 0o600)
os.chmod(dhclient_conf, 0o644)
# Make root own them
print "chowning configuration files root:root..."
print("chowning configuration files root:root...")
os.chown(app_conf.get_config(), 0, 0)
os.chown(wireless_conf, 0, 0)
os.chown(wired_conf, 0, 0)
os.chown(dhclient_conf, 0, 0)
print "Using wireless interface..." + self.GetWirelessInterface()
print "Using wired interface..." + self.GetWiredInterface()
print("Using wireless interface..." + self.GetWirelessInterface())
print("Using wired interface..." + self.GetWiredInterface())
##############################
###### Wireless Daemon #######
@@ -1004,10 +1004,10 @@ class WirelessDaemon(dbus.service.Object, object):
"""
if self._scanning:
if self.debug_mode:
print "scan already in progress, skipping"
print("scan already in progress, skipping")
return False
if self.debug_mode:
print 'scanning start'
print('scanning start')
self.SendStartScanSignal()
if sync:
self._sync_scan()
@@ -1025,8 +1025,8 @@ class WirelessDaemon(dbus.service.Object, object):
scan = self.wifi.Scan(str(self.hidden_essid))
self.LastScan = scan
if self.debug_mode:
print 'scanning done'
print 'found ' + str(len(scan)) + ' networks:'
print('scanning done')
print('found ' + str(len(scan)) + ' networks:')
for i, network in enumerate(scan):
self.ReadWirelessNetworkProfile(i)
self.SendEndScanSignal()
@@ -1115,8 +1115,8 @@ class WirelessDaemon(dbus.service.Object, object):
# We don't write script settings here.
prop = misc.sanitize_config(prop)
if prop.endswith('script'):
print 'Setting script properties through the daemon' \
+ ' is not permitted.'
print('Setting script properties through the daemon' \
+ ' is not permitted.')
return False
# whitelist some props that need different handling
if prop in ('key_index', ):
@@ -1130,9 +1130,9 @@ class WirelessDaemon(dbus.service.Object, object):
""" Returns an automatically detected wireless interface. """
iface = self.wifi.DetectWirelessInterface()
if iface:
print 'Automatically detected wireless interface ' + iface
print('Automatically detected wireless interface ' + iface)
else:
print "Couldn't detect a wireless interface."
print("Couldn't detect a wireless interface.")
return str(iface)
@dbus.service.method('org.wicd.daemon.wireless')
@@ -1174,11 +1174,11 @@ class WirelessDaemon(dbus.service.Object, object):
def GetCurrentNetworkID(self, iwconfig=None):
""" Returns the id of the current network, or -1 if its not found. """
currentESSID = self.GetCurrentNetwork(iwconfig)
for x in xrange(0, len(self.LastScan)):
for x in range(0, len(self.LastScan)):
if self.LastScan[x]['essid'] == currentESSID:
return x
if self.debug_mode:
print 'GetCurrentNetworkID: Returning -1, current network not found'
print('GetCurrentNetworkID: Returning -1, current network not found')
return -1
@dbus.service.method('org.wicd.daemon.wireless')
@@ -1209,8 +1209,8 @@ class WirelessDaemon(dbus.service.Object, object):
self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate')
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid,
'allow_lower_bitrates')
print 'Connecting to wireless network ' + \
str(self.LastScan[nid]['essid'])
print('Connecting to wireless network ' + \
str(self.LastScan[nid]['essid']))
# disconnect to make sure that scripts are run
self.wifi.Disconnect()
self.daemon.wired_bus.wired.Disconnect()
@@ -1265,7 +1265,7 @@ class WirelessDaemon(dbus.service.Object, object):
return "500: Profile Not Found"
for x in self.config.options(section):
if not cur_network.has_key(x) or x.endswith("script"):
if x not in cur_network or x.endswith("script"):
cur_network[x] = misc.Noneify(self.config.get(section, x))
for option in ['use_static_dns', 'use_global_dns', 'encryption',
'use_settings_globally']:
@@ -1325,8 +1325,8 @@ class WirelessDaemon(dbus.service.Object, object):
""" Writes a particular wireless property to disk. """
option = misc.sanitize_config(option)
if option.endswith("script"):
print 'You cannot save script information to disk through ' + \
'the daemon.'
print('You cannot save script information to disk through ' + \
'the daemon.')
return
config = self.config
cur_network = self.LastScan[nid]
@@ -1376,8 +1376,8 @@ class WirelessDaemon(dbus.service.Object, object):
def DeleteWirelessNetwork(self, section):
""" Deletes a wireless network section. """
section = misc.to_unicode(section)
print "Deleting wireless settings for %s (%s)" % \
(self.config.get(section, 'essid'), str(section))
print("Deleting wireless settings for %s (%s)" % \
(self.config.get(section, 'essid'), str(section)))
self.config.remove_section(section)
self.config.write()
@@ -1395,10 +1395,10 @@ class WirelessDaemon(dbus.service.Object, object):
def _wireless_autoconnect(self, fresh=True):
""" Attempts to autoconnect to a wireless network. """
print "No wired connection present, attempting to autoconnect " + \
"to wireless network"
print("No wired connection present, attempting to autoconnect " + \
"to wireless network")
if self.wifi.wireless_interface is None:
print 'Autoconnect failed because wireless interface returned None'
print('Autoconnect failed because wireless interface returned None')
return
if fresh:
self.Scan(sync=True)
@@ -1406,19 +1406,19 @@ class WirelessDaemon(dbus.service.Object, object):
for x, network in enumerate(self.LastScan):
if self.config.has_section(network['bssid']):
if self.debug_mode:
print network["essid"] + ' has profile'
print(network["essid"] + ' has profile')
if bool(network.get('automatic')):
if network.get('never'):
print network["essid"],'marked never connect'
print(network["essid"],'marked never connect')
continue
else:
print network["essid"],'has no never connect value'
print 'trying to automatically connect to...' + \
network["essid"]
print(network["essid"],'has no never connect value')
print('trying to automatically connect to...' + \
network["essid"])
self.ConnectWireless(x)
time.sleep(1)
return
print "Unable to autoconnect, you'll have to manually connect"
print("Unable to autoconnect, you'll have to manually connect")
###########################
###### Wired Daemon #######
@@ -1481,9 +1481,9 @@ class WiredDaemon(dbus.service.Object, object):
""" Returns an automatically detected wireless interface. """
iface = self.wired.DetectWiredInterface()
if iface:
print 'automatically detected wired interface ' + str(iface)
print('automatically detected wired interface ' + str(iface))
else:
print "Couldn't detect a wired interface."
print("Couldn't detect a wired interface.")
return str(iface)
@dbus.service.method('org.wicd.daemon.wired')
@@ -1492,13 +1492,13 @@ class WiredDaemon(dbus.service.Object, object):
if self.WiredNetwork:
prop = misc.sanitize_config(prop)
if prop.endswith('script'):
print 'Setting script properties through the daemon' \
+ ' is not permitted.'
print('Setting script properties through the daemon' \
+ ' is not permitted.')
return False
self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value))
return True
else:
print 'SetWiredProperty: WiredNetwork does not exist'
print('SetWiredProperty: WiredNetwork does not exist')
return False
@dbus.service.method('org.wicd.daemon.wired')
@@ -1508,7 +1508,7 @@ class WiredDaemon(dbus.service.Object, object):
value = self.WiredNetwork.get(prop)
return value
else:
print 'GetWiredProperty: WiredNetwork does not exist'
print('GetWiredProperty: WiredNetwork does not exist')
return False
@dbus.service.method('org.wicd.daemon.wired')
@@ -1572,7 +1572,7 @@ class WiredDaemon(dbus.service.Object, object):
if not profilename:
return False
profilename = misc.to_unicode(profilename)
print "Creating wired profile for " + profilename
print("Creating wired profile for " + profilename)
if self.config.has_section(profilename):
return False
@@ -1624,7 +1624,7 @@ class WiredDaemon(dbus.service.Object, object):
def DeleteWiredNetworkProfile(self, profilename):
""" Deletes a wired network profile. """
profilename = misc.to_unicode(profilename)
print "Deleting wired profile for " + str(profilename)
print("Deleting wired profile for " + str(profilename))
self.config.remove_section(profilename)
self.config.write()
@@ -1638,10 +1638,10 @@ class WiredDaemon(dbus.service.Object, object):
profilename = profilename.strip()
if not profilename:
self.config.write()
print "Warning: Bad wired profile name given, ignoring."
print("Warning: Bad wired profile name given, ignoring.")
return "500: Bad Profile name"
if self.debug_mode:
print "saving wired profile %s" % profilename
print("saving wired profile %s" % profilename)
profilename = misc.to_unicode(profilename)
self.config.remove_section(profilename)
self.config.add_section(profilename)
@@ -1662,7 +1662,7 @@ class WiredDaemon(dbus.service.Object, object):
profilename = misc.to_unicode(profilename)
if self.config.has_section(profilename):
if self.debug_mode:
print "Reading wired profile %s" % profilename
print("Reading wired profile %s" % profilename)
for x in self.config.options(profilename):
profile[x] = misc.Noneify(self.config.get(profilename, x))
profile['use_global_dns'] = bool(profile.get('use_global_dns'))
@@ -1698,7 +1698,7 @@ class WiredDaemon(dbus.service.Object, object):
def usage():
""" Print help screen. """
print """
print("""
wicd %s
wireless (and wired) connection daemon.
@@ -1710,7 +1710,7 @@ Arguments:
\t-n\t--no-poll\tDon't monitor network status.
\t-o\t--no-stdout\tDon't redirect stdout.
\t-h\t--help\t\tPrint this help.
""" % (wpath.version + ' (bzr-r%s)' % wpath.revision)
""" % (wpath.version + ' (bzr-r%s)' % wpath.revision))
def daemonize():
""" Disconnect from the controlling terminal.
@@ -1729,8 +1729,8 @@ def daemonize():
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
print >> sys.stderr, "Fork #1 failed: %d (%s)" % (e.errno, e.strerror)
except OSError as e:
print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
sys.exit(1)
# Decouple from parent environment to stop us from being a zombie.
@@ -1751,8 +1751,8 @@ def daemonize():
else:
os.umask(0)
os.chdir('/')
except OSError, e:
print >> sys.stderr, "Fork #2 failed: %d (%s)" % (e.errno, e.strerror)
except OSError as e:
print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
sys.exit(1)
sys.stdin.close()
@@ -1795,9 +1795,9 @@ def main(argv):
os.symlink(dest, backup_location)
else:
shutil.copy2('/etc/resolv.conf', backup_location)
os.chmod(backup_location, 0644)
os.chmod(backup_location, 0o644)
except IOError:
print 'error backing up resolv.conf'
print('error backing up resolv.conf')
do_daemonize = True
redirect_stderr = True
@@ -1852,9 +1852,9 @@ def main(argv):
os.symlink(dest, '/etc/resolv.conf')
else:
shutil.move(backup_location, '/etc/resolv.conf')
os.chmod('/etc/resolv.conf', 0644)
os.chmod('/etc/resolv.conf', 0o644)
except IOError:
print 'error restoring resolv.conf'
print('error restoring resolv.conf')
# connect to dbus, trigger a disconnect, then knock out the daemon
from wicd import dbusmanager
@@ -1869,8 +1869,8 @@ def main(argv):
sys.exit(0)
if os.path.exists(wpath.pidfile):
print 'It seems like the daemon is already running.'
print 'If it is not, please remove %s and try again.' % wpath.pidfile
print('It seems like the daemon is already running.')
print('If it is not, please remove %s and try again.' % wpath.pidfile)
sys.exit(1)
if not os.path.exists(wpath.networks):
@@ -1883,13 +1883,13 @@ def main(argv):
logpath = os.path.join(wpath.log, 'wicd.log')
if not os.path.exists(wpath.log):
os.makedirs(wpath.log)
os.chmod(wpath.log, 0755)
os.chmod(wpath.log, 0o755)
output = ManagedStdio(logpath)
if os.path.exists(logpath):
try:
os.chmod(logpath, int(wpath.log_perms, 8))
except OSError:
print 'unable to chmod log file to %s' % wpath.log_perms
print('unable to chmod log file to %s' % wpath.log_perms)
try:
if wpath.log_group:
@@ -1897,18 +1897,18 @@ def main(argv):
group = grp.getgrnam(wpath.log_group)
os.chown(logpath, 0, group[2])
except OSError:
print 'unable to chown log file to %s' % group[2]
print('unable to chown log file to %s' % group[2])
if redirect_stdout:
sys.stdout = output
if redirect_stderr:
sys.stderr = output
print '---------------------------'
print 'wicd initializing...'
print '---------------------------'
print('---------------------------')
print('wicd initializing...')
print('---------------------------')
print 'wicd is version', wpath.version, wpath.revision
print('wicd is version', wpath.version, wpath.revision)
# Open the DBUS session
bus = dbus.SystemBus()
@@ -1933,22 +1933,22 @@ def main(argv):
def on_exit(child_pid):
""" Called when a SIGTERM is caught, kills monitor.py before exiting. """
if child_pid:
print 'Daemon going down, killing wicd-monitor...'
print('Daemon going down, killing wicd-monitor...')
try:
os.kill(child_pid, signal.SIGTERM)
except OSError:
pass
print 'Removing PID file...'
print('Removing PID file...')
if os.path.exists(wpath.pidfile):
os.remove(wpath.pidfile)
print 'Shutting down...'
print('Shutting down...')
sys.exit(0)
if __name__ == '__main__':
if os.getuid() != 0:
print ("Root privileges are required for the daemon to run properly." +
" Exiting.")
print(("Root privileges are required for the daemon to run properly." +
" Exiting."))
sys.exit(1)
gobject.threads_init()
main(sys.argv)

View File

@@ -41,8 +41,8 @@ import socket, fcntl
import shutil
import wpath
import misc
from misc import find_path
from . import misc
from .misc import find_path
# Regular expressions.
_re_mode = (re.I | re.M | re.S)
@@ -129,7 +129,7 @@ def GetDefaultGateway():
gateway = None
for line in lines:
words = line.split()
print words
print(words)
if not words:
continue
if words[0] == '0.0.0.0':
@@ -137,7 +137,7 @@ def GetDefaultGateway():
break
if not gateway:
print 'couldn\'t retrieve default gateway from route -n'
print('couldn\'t retrieve default gateway from route -n')
return gateway
def isWireless(devname):
@@ -196,7 +196,7 @@ def GetWpaSupplicantDrivers():
try:
output = output.split("drivers:")[1].split("options:")[0].strip()
except KeyError:
print "Warning: Couldn't get list of valid wpa_supplicant drivers"
print("Warning: Couldn't get list of valid wpa_supplicant drivers")
return [""]
patt = re.compile("(\S+)\s+=.*")
drivers = patt.findall(output) or [""]
@@ -292,7 +292,7 @@ class BaseInterface(object):
"""
path = find_path(program)
if not path and self.verbose:
print "WARNING: No path found for %s" % program
print("WARNING: No path found for %s" % program)
return path
@@ -363,8 +363,8 @@ class BaseInterface(object):
# for specifing the hostname to be sent
if client_name == "dhclient" and flavor:
if hostname:
print 'attempting to set hostname with dhclient'
print 'using dhcpcd or another supported client may work better'
print('attempting to set hostname with dhclient')
print('using dhcpcd or another supported client may work better')
dhclient_template = \
open(os.path.join(wpath.etc, 'dhclient.conf.template'), 'r')
@@ -381,10 +381,10 @@ class BaseInterface(object):
shutil.copy(os.path.join(wpath.etc, 'dhclient.conf.template'), \
dhclient_conf_path)
os.chmod(dhclient_conf_path, 0644)
os.chmod(dhclient_conf_path, 0o644)
if not client_name or not cmd:
print "WARNING: Failed to find a valid dhcp client!"
print("WARNING: Failed to find a valid dhcp client!")
return ""
if flavor == "connect":
@@ -468,7 +468,7 @@ class BaseInterface(object):
""" Check for the existence of wpa_cli """
self.wpa_cli_cmd = self._find_program_path("wpa_cli")
if not self.wpa_cli_cmd:
print "wpa_cli not found. Authentication will not be validated."
print("wpa_cli not found. Authentication will not be validated.")
def CheckRouteFlushTool(self):
""" Check for a route flush tool. """
@@ -491,7 +491,7 @@ class BaseInterface(object):
"""
cmd = 'ifconfig ' + self.iface + ' up'
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
return True
@@ -505,7 +505,7 @@ class BaseInterface(object):
"""
cmd = 'ifconfig ' + self.iface + ' down'
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
return True
@@ -515,7 +515,7 @@ class BaseInterface(object):
""" Runs ifconfig and returns the output. """
cmd = "ifconfig %s" % self.iface
if self.verbose:
print cmd
print(cmd)
return misc.Run(cmd)
@neediface("")
@@ -532,7 +532,7 @@ class BaseInterface(object):
if not val:
continue
if not misc.IsValidIP(val):
print 'WARNING: Invalid IP address found, aborting!'
print('WARNING: Invalid IP address found, aborting!')
return False
cmd = ''.join(['ifconfig ', self.iface, ' '])
@@ -543,7 +543,7 @@ class BaseInterface(object):
if broadcast:
cmd = ''.join([cmd, 'broadcast ', broadcast, ' '])
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
def _parse_dhclient(self, pipe):
@@ -567,7 +567,7 @@ class BaseInterface(object):
if line == '': # Empty string means dhclient is done.
dhclient_complete = True
else:
print misc.to_unicode(line.strip('\n'))
print(misc.to_unicode(line.strip('\n')))
if line.startswith('bound'):
dhclient_success = True
dhclient_complete = True
@@ -594,7 +594,7 @@ class BaseInterface(object):
elif line.strip().lower().startswith('Operation failed.'):
pump_success = False
pump_complete = True
print misc.to_unicode(line)
print(misc.to_unicode(line))
return self._check_dhcp_result(pump_success)
@@ -618,7 +618,7 @@ class BaseInterface(object):
dhcpcd_complete = True
elif line == '':
dhcpcd_complete = True
print misc.to_unicode(line)
print(misc.to_unicode(line))
return self._check_dhcp_result(dhcpcd_success)
@@ -642,7 +642,7 @@ class BaseInterface(object):
udhcpc_complete = True
elif line == '':
udhcpc_complete = True
print line
print(line)
return self._check_dhcp_result(udhcpc_success)
@@ -657,10 +657,10 @@ class BaseInterface(object):
"""
if success:
print 'DHCP connection successful'
print('DHCP connection successful')
return 'success'
else:
print 'DHCP connection failed'
print('DHCP connection failed')
return 'dhcp_failed'
@neediface(False)
@@ -677,7 +677,7 @@ class BaseInterface(object):
"""
cmd = self._get_dhcp_command('connect', hostname, staticdns)
if self.verbose:
print cmd
print(cmd)
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
pipe = self.dhcp_object.stdout
client_dict = { misc.DHCLIENT : self._parse_dhclient,
@@ -690,7 +690,7 @@ class BaseInterface(object):
if DHCP_CLIENT in client_dict:
ret = client_dict[DHCP_CLIENT](pipe)
else:
print "ERROR: no dhcp client found"
print("ERROR: no dhcp client found")
ret = None
self.dhcp_object.wait()
return ret
@@ -700,7 +700,7 @@ class BaseInterface(object):
""" Release the DHCP lease for this interface. """
cmd = self._get_dhcp_command("release")
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface(False)
@@ -711,10 +711,10 @@ class BaseInterface(object):
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
cmd = '%s del default dev %s' % (self.route_cmd, self.iface)
else:
print "No route manipulation command available!"
print("No route manipulation command available!")
return
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface(False)
@@ -727,7 +727,7 @@ class BaseInterface(object):
if self.resolvconf_cmd:
cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd']
if self.verbose:
print cmd
print(cmd)
p = misc.Run(cmd, include_stderr=True, return_obj=True)
p.communicate()
@@ -757,10 +757,10 @@ class BaseInterface(object):
if dns:
if misc.IsValidIP(dns):
if self.verbose:
print 'Setting DNS : ' + dns
print('Setting DNS : ' + dns)
valid_dns_list.append("nameserver %s\n" % dns)
else:
print 'DNS IP %s is not a valid IP address, skipping' % dns
print('DNS IP %s is not a valid IP address, skipping' % dns)
if valid_dns_list:
resolv_params += ''.join(valid_dns_list)
@@ -768,7 +768,7 @@ class BaseInterface(object):
if self.resolvconf_cmd:
cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd']
if self.verbose:
print cmd
print(cmd)
p = misc.Run(cmd, include_stderr=True, return_obj=True)
p.communicate(input=resolv_params)
else:
@@ -784,11 +784,11 @@ class BaseInterface(object):
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
cmds = ['%s del dev %s' % (self.route_cmd, self.iface)]
else:
print "No flush command available!"
print("No flush command available!")
cmds = []
for cmd in cmds:
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface(False)
@@ -800,11 +800,11 @@ class BaseInterface(object):
"""
if not misc.IsValidIP(gw):
print 'WARNING: Invalid gateway found. Aborting!'
print('WARNING: Invalid gateway found. Aborting!')
return False
cmd = 'route add default gw %s dev %s' % (gw, self.iface)
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface("")
@@ -845,7 +845,7 @@ class BaseInterface(object):
# most.
cmd = "ping -q -c 1 %s" % gateway
if self.verbose:
print cmd
print(cmd)
return misc.LaunchAndWait(cmd)
@neediface(False)
@@ -860,8 +860,8 @@ class BaseInterface(object):
try:
flags = open(flags_file, "r").read().strip()
except IOError:
print "Could not open %s, using ifconfig to determine status" \
% flags_file
print("Could not open %s, using ifconfig to determine status" \
% flags_file)
return self._slow_is_up(ifconfig)
return bool(int(flags, 16) & 1)
@@ -870,7 +870,7 @@ class BaseInterface(object):
""" Terminates wpa using wpa_cli"""
cmd = 'wpa_cli -i %s terminate' % self.iface
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@@ -942,16 +942,16 @@ class BaseWiredInterface(BaseInterface):
elif link == 0:
return False
except (IOError, ValueError, TypeError):
print 'Error checking link using /sys/class/net/%s/carrier' \
% self.iface
print('Error checking link using /sys/class/net/%s/carrier' \
% self.iface)
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in()
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
return self._mii_get_plugged_in()
else:
print ('Error: No way of checking for a wired connection. Make ' +
'sure that either mii-tool or ethtool is installed.')
print(('Error: No way of checking for a wired connection. Make ' +
'sure that either mii-tool or ethtool is installed.'))
return False
def _eth_get_plugged_in(self):
@@ -963,11 +963,11 @@ class BaseWiredInterface(BaseInterface):
"""
cmd = "%s %s" % (self.ethtool_cmd, self.iface)
if not self.IsUp():
print 'Wired Interface is down, putting it up'
print('Wired Interface is down, putting it up')
self.Up()
time.sleep(6)
if self.verbose:
print cmd
print(cmd)
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(
re.compile('(Link detected: yes)', re.I | re.M | re.S),
@@ -986,15 +986,15 @@ class BaseWiredInterface(BaseInterface):
"""
cmd = "%s %s" % (self.miitool_cmd, self.iface)
if self.verbose:
print cmd
print(cmd)
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S),
tool_data) is not None:
print 'Wired Interface is down, putting it up'
print('Wired Interface is down, putting it up')
self.Up()
time.sleep(4)
if self.verbose:
print cmd
print(cmd)
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S),
@@ -1010,7 +1010,7 @@ class BaseWiredInterface(BaseInterface):
os.path.join(wpath.networks, 'wired'),
'-Dwired']
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
class BaseWirelessInterface(BaseInterface):
@@ -1041,7 +1041,7 @@ class BaseWirelessInterface(BaseInterface):
"""
cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)]
if self.verbose:
print str(cmd)
print(str(cmd))
misc.Run(cmd)
@neediface(False)
@@ -1068,7 +1068,7 @@ class BaseWirelessInterface(BaseInterface):
""" Returns the output of iwconfig for this interface. """
cmd = "iwconfig " + self.iface
if self.verbose:
print cmd
print(cmd)
return misc.Run(cmd)
def _FreqToChannel(self, freq):
@@ -1093,7 +1093,7 @@ class BaseWirelessInterface(BaseInterface):
try:
ret = freq_dict[freq]
except KeyError:
print "Couldn't determine channel number for frequency:", str(freq)
print("Couldn't determine channel number for frequency:", str(freq))
return ret
@@ -1107,7 +1107,7 @@ class BaseWirelessInterface(BaseInterface):
"""
iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey')
if self.verbose:
print iwpriv
print(iwpriv)
lines = iwpriv.splitlines()[2:]
aps = {}
patt = re.compile("((?:[0-9A-Z]{2}:){5}[0-9A-Z]{2})")
@@ -1124,7 +1124,7 @@ class BaseWirelessInterface(BaseInterface):
bssid = info[3].upper()
offset = 0
else: # Invalid
print 'Invalid iwpriv line. Skipping it.'
print('Invalid iwpriv line. Skipping it.')
continue
ap['nettype'] = info[-1]
ap['strength'] = info[1]
@@ -1146,11 +1146,11 @@ class BaseWirelessInterface(BaseInterface):
elif info[4 + offset] == "NONE":
ap['encryption_method'] = None
else:
print "Unknown AuthMode, can't assign encryption_method!"
print("Unknown AuthMode, can't assign encryption_method!")
ap['encryption_method'] = 'Unknown'
aps[bssid] = ap
if self.verbose:
print str(aps)
print(str(aps))
return aps
def _ParseRalinkAccessPoint(self, ap, ralink_info, cell):
@@ -1165,9 +1165,9 @@ class BaseWirelessInterface(BaseInterface):
Updated array containing info about the current access point
"""
if ralink_info.has_key(ap['bssid']):
if ap['bssid'] in ralink_info:
info = ralink_info[ap['bssid']]
for key in info.keys():
for key in list(info.keys()):
ap[key] = info[key]
if misc.RunRegex(wep_pattern, cell) == 'on':
ap['encryption'] = True
@@ -1190,7 +1190,7 @@ class BaseWirelessInterface(BaseInterface):
mode = 'managed'
cmd = 'iwconfig %s mode %s' % (self.iface, mode)
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface(False)
@@ -1202,12 +1202,12 @@ class BaseWirelessInterface(BaseInterface):
"""
if not channel.isdigit():
print 'WARNING: Invalid channel found. Aborting!'
print('WARNING: Invalid channel found. Aborting!')
return False
cmd = 'iwconfig %s channel %s' % (self.iface, str(channel))
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface(False)
@@ -1220,7 +1220,7 @@ class BaseWirelessInterface(BaseInterface):
"""
cmd = 'iwconfig %s key %s' % (self.iface, key)
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
@neediface(False)
@@ -1257,12 +1257,12 @@ class BaseWirelessInterface(BaseInterface):
if channel and str(channel).isdigit():
cmd = "%s channel %s" % (base, str(channel))
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
if bssid:
cmd = "%s ap %s" % (base, bssid)
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
def GeneratePSK(self, network):
@@ -1279,7 +1279,7 @@ class BaseWirelessInterface(BaseInterface):
re.I | re.M | re.S)
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
if self.verbose:
print cmd
print(cmd)
return misc.RunRegex(key_pattern, misc.Run(cmd))
@neediface(False)
@@ -1303,7 +1303,7 @@ class BaseWirelessInterface(BaseInterface):
network['bssid'].replace(':', '').lower()),
driver]
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
def _AuthenticateRalinkLegacy(self, network):
@@ -1320,16 +1320,16 @@ class BaseWirelessInterface(BaseInterface):
try:
info = self._GetRalinkInfo()[network.get('bssid')]
except KeyError:
print "Could not find current network in iwpriv " + \
"get_site_survey results. Cannot authenticate."
print("Could not find current network in iwpriv " + \
"get_site_survey results. Cannot authenticate.")
return
if info['enctype'] == "WEP" and info['authtype'] == 'OPEN':
print 'Setting up WEP'
print('Setting up WEP')
cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')])
if self.verbose:
print cmd
print(cmd)
misc.Run(cmd)
else:
cmd_list = []
@@ -1344,7 +1344,7 @@ class BaseWirelessInterface(BaseInterface):
for cmd in cmd_list:
cmd = ['iwpriv', self.iface, 'set', cmd]
if self.verbose:
print ' '.join(cmd)
print(' '.join(cmd))
misc.Run(cmd)
@neediface([])
@@ -1362,11 +1362,11 @@ class BaseWirelessInterface(BaseInterface):
# but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan.
essid = misc.Noneify(essid)
if essid is not None:
print 'Passing hidden essid to iwlist scan: ' + essid
print('Passing hidden essid to iwlist scan: ' + essid)
cmd = cmd + ' essid ' + essid
if self.verbose:
print cmd
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.
@@ -1397,7 +1397,7 @@ class BaseWirelessInterface(BaseInterface):
or not entry['hidden']):
access_points[entry['bssid']] = entry
return access_points.values()
return list(access_points.values())
def _ParseAccessPoint(self, cell, ralink_info):
""" Parse a single cell from the output of iwlist.
@@ -1416,7 +1416,7 @@ class BaseWirelessInterface(BaseInterface):
try:
ap['essid'] = misc.to_unicode(ap['essid'])
except (UnicodeDecodeError, UnicodeEncodeError):
print 'Unicode problem with current network essid, ignoring!!'
print('Unicode problem with current network essid, ignoring!!')
return None
# We (well, DBus) don't support ESSIDs with null bytes in it.
@@ -1425,7 +1425,7 @@ class BaseWirelessInterface(BaseInterface):
ap['essid'] = ap['essid'].replace('\x00', '')
if ap['essid'] in ['Hidden', '<hidden>', "", None]:
print 'hidden'
print('hidden')
ap['hidden'] = True
ap['essid'] = "<hidden>"
else:
@@ -1453,7 +1453,7 @@ class BaseWirelessInterface(BaseInterface):
# Mode
ap['mode'] = misc.RunRegex(mode_pattern, cell)
if ap['mode'] is None:
print 'Invalid network mode string, ignoring!'
print('Invalid network mode string, ignoring!')
return None
# Break off here if we're using a ralink card
@@ -1521,7 +1521,7 @@ class BaseWirelessInterface(BaseInterface):
output = misc.Run(cmd)
result = misc.RunRegex(auth_pattern, output)
if self.verbose:
print 'WPA_CLI RESULT IS', result
print('WPA_CLI RESULT IS', result)
if not result:
return False
@@ -1539,7 +1539,7 @@ class BaseWirelessInterface(BaseInterface):
disconnected_time = 0
time.sleep(1)
print 'wpa_supplicant authentication may have failed.'
print('wpa_supplicant authentication may have failed.')
return False
@@ -1554,7 +1554,7 @@ class BaseWirelessInterface(BaseInterface):
time, so we manually speed it up if we see it happening.
"""
print 'wpa_supplicant rescan forced...'
print('wpa_supplicant rescan forced...')
cmd = 'wpa_cli -i' + self.iface + ' scan'
misc.Run(cmd)
@@ -1599,7 +1599,7 @@ class BaseWirelessInterface(BaseInterface):
if not iwlistauth:
cmd = 'iwlist ' + self.iface + ' auth'
if self.verbose:
print cmd
print(cmd)
output = misc.Run(cmd)
else:
output = iwlistauth
@@ -1614,7 +1614,7 @@ class BaseWirelessInterface(BaseInterface):
cmd = 'iwlist ' + self.iface + ' rate'
if self.verbose:
print cmd
print(cmd)
rates = misc.Run(cmd)
# process the output