mirror of
https://github.com/gryf/wicd.git
synced 2025-12-19 12:28:08 +01:00
2to3 transformation
This commit is contained in:
@@ -28,3 +28,4 @@ wicd/wpath.py
|
|||||||
dist/
|
dist/
|
||||||
MANIFEST
|
MANIFEST
|
||||||
debian/
|
debian/
|
||||||
|
.vscode/
|
||||||
|
|||||||
118
cli/wicd-cli.py
118
cli/wicd-cli.py
@@ -52,13 +52,13 @@ try:
|
|||||||
'org.wicd.daemon.config'
|
'org.wicd.daemon.config'
|
||||||
)
|
)
|
||||||
except dbus.DBusException:
|
except dbus.DBusException:
|
||||||
print 'Error: Could not connect to the daemon. ' + \
|
print('Error: Could not connect to the daemon. ' + \
|
||||||
'Please make sure it is running.'
|
'Please make sure it is running.')
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
if not daemon:
|
if not daemon:
|
||||||
print 'Error connecting to wicd via D-Bus. ' + \
|
print('Error connecting to wicd via D-Bus. ' + \
|
||||||
'Please make sure the wicd service is running.'
|
'Please make sure the wicd service is running.')
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
parser = optparse.OptionParser()
|
parser = optparse.OptionParser()
|
||||||
@@ -88,8 +88,8 @@ options, arguments = parser.parse_args()
|
|||||||
op_performed = False
|
op_performed = False
|
||||||
|
|
||||||
if not (options.wireless or options.wired) and not options.status:
|
if not (options.wireless or options.wired) and not options.status:
|
||||||
print "Please use --wireless or --wired to specify " + \
|
print("Please use --wireless or --wired to specify " + \
|
||||||
"the type of connection to operate on."
|
"the type of connection to operate on.")
|
||||||
|
|
||||||
if options.status:
|
if options.status:
|
||||||
status, info = daemon.GetConnectionStatus()
|
status, info = daemon.GetConnectionStatus()
|
||||||
@@ -104,27 +104,27 @@ if options.status:
|
|||||||
connected = False
|
connected = False
|
||||||
status_msg = misc._const_status_dict[status]
|
status_msg = misc._const_status_dict[status]
|
||||||
|
|
||||||
print _('Connection status') + ': ' + status_msg
|
print(_('Connection status') + ': ' + status_msg)
|
||||||
if connected:
|
if connected:
|
||||||
print _('Connection type') + ': ' + conn_type
|
print(_('Connection type') + ': ' + conn_type)
|
||||||
if status == misc.WIRELESS:
|
if status == misc.WIRELESS:
|
||||||
strength = daemon.FormatSignalForPrinting(info[2])
|
strength = daemon.FormatSignalForPrinting(info[2])
|
||||||
print _('Connected to $A at $B (IP: $C)') \
|
print(_('Connected to $A at $B (IP: $C)') \
|
||||||
.replace('$A', info[1]) \
|
.replace('$A', info[1]) \
|
||||||
.replace('$B', strength) \
|
.replace('$B', strength) \
|
||||||
.replace('$C', info[0])
|
.replace('$C', info[0]))
|
||||||
print _('Network ID: $A') \
|
print(_('Network ID: $A') \
|
||||||
.replace('$A', info[3])
|
.replace('$A', info[3]))
|
||||||
else:
|
else:
|
||||||
print _('Connected to wired network (IP: $A)') \
|
print(_('Connected to wired network (IP: $A)') \
|
||||||
.replace('$A', info[0])
|
.replace('$A', info[0]))
|
||||||
else:
|
else:
|
||||||
if status == misc.CONNECTING:
|
if status == misc.CONNECTING:
|
||||||
if info[0] == 'wired':
|
if info[0] == 'wired':
|
||||||
print _('Connecting to wired network.')
|
print(_('Connecting to wired network.'))
|
||||||
elif info[0] == 'wireless':
|
elif info[0] == 'wireless':
|
||||||
print _('Connecting to wireless network "$A".') \
|
print(_('Connecting to wireless network "$A".') \
|
||||||
.replace('$A', info[1])
|
.replace('$A', info[1]))
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
# functions
|
# functions
|
||||||
@@ -132,7 +132,7 @@ def is_valid_wireless_network_id(network_id):
|
|||||||
""" Check if it's a valid wireless network. '"""
|
""" Check if it's a valid wireless network. '"""
|
||||||
if not (network_id >= 0 \
|
if not (network_id >= 0 \
|
||||||
and network_id < wireless.GetNumberOfNetworks()):
|
and network_id < wireless.GetNumberOfNetworks()):
|
||||||
print 'Invalid wireless network identifier.'
|
print('Invalid wireless network identifier.')
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def is_valid_wired_network_id(network_id):
|
def is_valid_wired_network_id(network_id):
|
||||||
@@ -140,13 +140,13 @@ def is_valid_wired_network_id(network_id):
|
|||||||
num = len(wired.GetWiredProfileList())
|
num = len(wired.GetWiredProfileList())
|
||||||
if not (network_id < num and \
|
if not (network_id < num and \
|
||||||
network_id >= 0):
|
network_id >= 0):
|
||||||
print 'Invalid wired network identifier.'
|
print('Invalid wired network identifier.')
|
||||||
sys.exit(4)
|
sys.exit(4)
|
||||||
|
|
||||||
def is_valid_wired_network_profile(profile_name):
|
def is_valid_wired_network_profile(profile_name):
|
||||||
""" Check if it's a valid wired network profile. '"""
|
""" Check if it's a valid wired network profile. '"""
|
||||||
if not profile_name in wired.GetWiredProfileList():
|
if not profile_name in wired.GetWiredProfileList():
|
||||||
print 'Profile of that name does not exist.'
|
print('Profile of that name does not exist.')
|
||||||
sys.exit(5)
|
sys.exit(5)
|
||||||
|
|
||||||
if options.scan and options.wireless:
|
if options.scan and options.wireless:
|
||||||
@@ -161,17 +161,17 @@ if options.load_profile and options.wired:
|
|||||||
|
|
||||||
if options.list_networks:
|
if options.list_networks:
|
||||||
if options.wireless:
|
if options.wireless:
|
||||||
print '#\tBSSID\t\t\tChannel\tESSID'
|
print('#\tBSSID\t\t\tChannel\tESSID')
|
||||||
for network_id in range(0, wireless.GetNumberOfNetworks()):
|
for network_id in range(0, wireless.GetNumberOfNetworks()):
|
||||||
print '%s\t%s\t%s\t%s' % (network_id,
|
print('%s\t%s\t%s\t%s' % (network_id,
|
||||||
wireless.GetWirelessProperty(network_id, 'bssid'),
|
wireless.GetWirelessProperty(network_id, 'bssid'),
|
||||||
wireless.GetWirelessProperty(network_id, 'channel'),
|
wireless.GetWirelessProperty(network_id, 'channel'),
|
||||||
wireless.GetWirelessProperty(network_id, 'essid'))
|
wireless.GetWirelessProperty(network_id, 'essid')))
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
print '#\tProfile name'
|
print('#\tProfile name')
|
||||||
i = 0
|
i = 0
|
||||||
for profile in wired.GetWiredProfileList():
|
for profile in wired.GetWiredProfileList():
|
||||||
print '%s\t%s' % (i, profile)
|
print('%s\t%s' % (i, profile))
|
||||||
i += 1
|
i += 1
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
@@ -184,24 +184,24 @@ if options.network_details:
|
|||||||
network_id = wireless.GetCurrentNetworkID(0)
|
network_id = wireless.GetCurrentNetworkID(0)
|
||||||
is_valid_wireless_network_id(network_id)
|
is_valid_wireless_network_id(network_id)
|
||||||
# we're connected to a network, print IP
|
# we're connected to a network, print IP
|
||||||
print "IP: %s" % wireless.GetWirelessIP(0)
|
print("IP: %s" % wireless.GetWirelessIP(0))
|
||||||
|
|
||||||
print "Essid: %s" % wireless.GetWirelessProperty(network_id, "essid")
|
print("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))
|
||||||
print "Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid")
|
print("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))
|
||||||
if wireless.GetWirelessProperty(network_id, "encryption"):
|
if wireless.GetWirelessProperty(network_id, "encryption"):
|
||||||
print "Encryption: On"
|
print("Encryption: On")
|
||||||
print "Encryption Method: %s" % \
|
print("Encryption Method: %s" % \
|
||||||
wireless.GetWirelessProperty(network_id, "encryption_method")
|
wireless.GetWirelessProperty(network_id, "encryption_method"))
|
||||||
else:
|
else:
|
||||||
print "Encryption: Off"
|
print("Encryption: Off")
|
||||||
print "Quality: %s" % \
|
print("Quality: %s" % \
|
||||||
wireless.GetWirelessProperty(network_id, "quality")
|
wireless.GetWirelessProperty(network_id, "quality"))
|
||||||
print "Mode: %s" % \
|
print("Mode: %s" % \
|
||||||
wireless.GetWirelessProperty(network_id, "mode")
|
wireless.GetWirelessProperty(network_id, "mode"))
|
||||||
print "Channel: %s" % \
|
print("Channel: %s" % \
|
||||||
wireless.GetWirelessProperty(network_id, "channel")
|
wireless.GetWirelessProperty(network_id, "channel"))
|
||||||
print "Bit Rates: %s" % \
|
print("Bit Rates: %s" % \
|
||||||
wireless.GetWirelessProperty(network_id, "bitrates")
|
wireless.GetWirelessProperty(network_id, "bitrates"))
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
# network properties
|
# network properties
|
||||||
@@ -216,14 +216,14 @@ if options.network_property:
|
|||||||
network_id = wireless.GetCurrentNetworkID(0)
|
network_id = wireless.GetCurrentNetworkID(0)
|
||||||
is_valid_wireless_network_id(network_id)
|
is_valid_wireless_network_id(network_id)
|
||||||
if not options.set_to:
|
if not options.set_to:
|
||||||
print wireless.GetWirelessProperty(network_id,
|
print(wireless.GetWirelessProperty(network_id,
|
||||||
options.network_property)
|
options.network_property))
|
||||||
else:
|
else:
|
||||||
wireless.SetWirelessProperty(network_id, \
|
wireless.SetWirelessProperty(network_id, \
|
||||||
options.network_property, options.set_to)
|
options.network_property, options.set_to)
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
if not options.set_to:
|
if not options.set_to:
|
||||||
print wired.GetWiredProperty(options.network_property)
|
print(wired.GetWiredProperty(options.network_property))
|
||||||
else:
|
else:
|
||||||
wired.SetWiredProperty(options.network_property, options.set_to)
|
wired.SetWiredProperty(options.network_property, options.set_to)
|
||||||
op_performed = True
|
op_performed = True
|
||||||
@@ -232,13 +232,13 @@ if options.disconnect:
|
|||||||
daemon.Disconnect()
|
daemon.Disconnect()
|
||||||
if options.wireless:
|
if options.wireless:
|
||||||
if wireless.GetCurrentNetworkID(0) > -1:
|
if wireless.GetCurrentNetworkID(0) > -1:
|
||||||
print "Disconnecting from %s on %s" % \
|
print("Disconnecting from %s on %s" % \
|
||||||
(wireless.GetCurrentNetwork(0),
|
(wireless.GetCurrentNetwork(0),
|
||||||
wireless.DetectWirelessInterface())
|
wireless.DetectWirelessInterface()))
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
if wired.CheckPluggedIn():
|
if wired.CheckPluggedIn():
|
||||||
print "Disconnecting from wired connection on %s" % \
|
print("Disconnecting from wired connection on %s" % \
|
||||||
wired.DetectWiredInterface()
|
wired.DetectWiredInterface())
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
if options.connect:
|
if options.connect:
|
||||||
@@ -247,16 +247,16 @@ if options.connect:
|
|||||||
is_valid_wireless_network_id(options.network)
|
is_valid_wireless_network_id(options.network)
|
||||||
name = wireless.GetWirelessProperty(options.network, 'essid')
|
name = wireless.GetWirelessProperty(options.network, 'essid')
|
||||||
encryption = wireless.GetWirelessProperty(options.network, 'enctype')
|
encryption = wireless.GetWirelessProperty(options.network, 'enctype')
|
||||||
print "Connecting to %s with %s on %s" % (name, encryption,
|
print("Connecting to %s with %s on %s" % (name, encryption,
|
||||||
wireless.DetectWirelessInterface())
|
wireless.DetectWirelessInterface()))
|
||||||
wireless.ConnectWireless(options.network)
|
wireless.ConnectWireless(options.network)
|
||||||
|
|
||||||
check = wireless.CheckIfWirelessConnecting
|
check = wireless.CheckIfWirelessConnecting
|
||||||
status = wireless.CheckWirelessConnectingStatus
|
status = wireless.CheckWirelessConnectingStatus
|
||||||
message = wireless.CheckWirelessConnectingMessage
|
message = wireless.CheckWirelessConnectingMessage
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
print "Connecting to wired connection on %s" % \
|
print("Connecting to wired connection on %s" % \
|
||||||
wired.DetectWiredInterface()
|
wired.DetectWiredInterface())
|
||||||
wired.ConnectWired()
|
wired.ConnectWired()
|
||||||
|
|
||||||
check = wired.CheckIfWiredConnecting
|
check = wired.CheckIfWiredConnecting
|
||||||
@@ -277,10 +277,10 @@ if options.connect:
|
|||||||
# the loop check
|
# the loop check
|
||||||
if next_ == "done":
|
if next_ == "done":
|
||||||
break
|
break
|
||||||
print message()
|
print(message())
|
||||||
last = next_
|
last = next_
|
||||||
print "done!"
|
print("done!")
|
||||||
if status() != u'done':
|
if status() != 'done':
|
||||||
exit_status = 6
|
exit_status = 6
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
@@ -295,12 +295,12 @@ def str_properties(prop):
|
|||||||
if options.wireless and options.list_encryption_types:
|
if options.wireless and options.list_encryption_types:
|
||||||
et = misc.LoadEncryptionMethods()
|
et = misc.LoadEncryptionMethods()
|
||||||
# print 'Installed encryption templates:'
|
# print 'Installed encryption templates:'
|
||||||
print '%s\t%-20s\t%s' % ('#', 'Name', 'Description')
|
print('%s\t%-20s\t%s' % ('#', 'Name', 'Description'))
|
||||||
i = 0
|
i = 0
|
||||||
for t in et:
|
for t in et:
|
||||||
print '%s\t%-20s\t%s' % (i, t['type'], t['name'])
|
print('%s\t%-20s\t%s' % (i, t['type'], t['name']))
|
||||||
print ' Req: %s' % str_properties(t['required'])
|
print(' Req: %s' % str_properties(t['required']))
|
||||||
print '---'
|
print('---')
|
||||||
# don't print optionals (yet)
|
# don't print optionals (yet)
|
||||||
#print ' Opt: %s' % str_properties(type['optional'])
|
#print ' Opt: %s' % str_properties(type['optional'])
|
||||||
i += 1
|
i += 1
|
||||||
@@ -315,7 +315,7 @@ if options.save and options.network > -1:
|
|||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
if not op_performed:
|
if not op_performed:
|
||||||
print "No operations performed."
|
print("No operations performed.")
|
||||||
|
|
||||||
sys.exit(exit_status)
|
sys.exit(exit_status)
|
||||||
|
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ def main(argv):
|
|||||||
""" Main function. """
|
""" Main function. """
|
||||||
global ui, frame
|
global ui, frame
|
||||||
if len(argv) < 2:
|
if len(argv) < 2:
|
||||||
print 'Network id to configure is missing, aborting.'
|
print('Network id to configure is missing, aborting.')
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
ui = urwid.curses_display.Screen()
|
ui = urwid.curses_display.Screen()
|
||||||
@@ -161,6 +161,6 @@ def run():
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if os.getuid() != 0:
|
if os.getuid() != 0:
|
||||||
print "Root privileges are required to configure scripts. Exiting."
|
print("Root privileges are required to configure scripts. Exiting.")
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
main(sys.argv)
|
main(sys.argv)
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ wicd-curses.
|
|||||||
import urwid
|
import urwid
|
||||||
|
|
||||||
from wicd.translations import _
|
from wicd.translations import _
|
||||||
|
from functools import reduce
|
||||||
|
|
||||||
|
|
||||||
# Uses code that is towards the bottom
|
# Uses code that is towards the bottom
|
||||||
@@ -185,13 +186,12 @@ class MaskingEdit(urwid.Edit):
|
|||||||
""" Get masked out text. """
|
""" Get masked out text. """
|
||||||
return self.mask_char * len(self.get_edit_text())
|
return self.mask_char * len(self.get_edit_text())
|
||||||
|
|
||||||
def render(self, (maxcol, ), focus=False):
|
def render(self, xxx_todo_changeme, focus=False):
|
||||||
"""
|
"""
|
||||||
Render edit widget and return canvas. Include cursor when in
|
Render edit widget and return canvas. Include cursor when in
|
||||||
focus.
|
focus.
|
||||||
"""
|
"""
|
||||||
# If we aren't masking anything ATM, then act like an Edit.
|
(maxcol, ) = xxx_todo_changeme
|
||||||
# No problems.
|
|
||||||
if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
|
if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
|
||||||
# pylint: disable-msg=E1101
|
# pylint: disable-msg=E1101
|
||||||
canv = self.__super.render((maxcol, ), focus)
|
canv = self.__super.render((maxcol, ), focus)
|
||||||
@@ -235,7 +235,7 @@ class TabColumns(urwid.WidgetWrap):
|
|||||||
column_list.append(('fixed', len(text), w))
|
column_list.append(('fixed', len(text), w))
|
||||||
column_list.append(urwid.Text((attrtitle, title), align='right'))
|
column_list.append(urwid.Text((attrtitle, title), align='right'))
|
||||||
|
|
||||||
self.tab_map = dict(zip(tab_str, tab_wid))
|
self.tab_map = dict(list(zip(tab_str, tab_wid)))
|
||||||
self.active_tab = tab_str[0]
|
self.active_tab = tab_str[0]
|
||||||
self.columns = urwid.Columns(column_list, dividechars=1)
|
self.columns = urwid.Columns(column_list, dividechars=1)
|
||||||
#walker = urwid.SimpleListWalker([self.columns, tab_wid[0]])
|
#walker = urwid.SimpleListWalker([self.columns, tab_wid[0]])
|
||||||
@@ -606,7 +606,7 @@ class Dialog2(urwid.WidgetWrap):
|
|||||||
raise DialogExit(-1)
|
raise DialogExit(-1)
|
||||||
if k:
|
if k:
|
||||||
self.unhandled_key(size, k)
|
self.unhandled_key(size, k)
|
||||||
except DialogExit, e:
|
except DialogExit as e:
|
||||||
return self.on_exit(e.args[0])
|
return self.on_exit(e.args[0])
|
||||||
|
|
||||||
def on_exit(self, exitcode):
|
def on_exit(self, exitcode):
|
||||||
|
|||||||
@@ -402,7 +402,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
|
|||||||
bool(wired.GetWiredProperty('usedhcphostname'))
|
bool(wired.GetWiredProperty('usedhcphostname'))
|
||||||
)
|
)
|
||||||
self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state())
|
self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state())
|
||||||
self.dhcp_h.set_edit_text(unicode(dhcphname))
|
self.dhcp_h.set_edit_text(str(dhcphname))
|
||||||
|
|
||||||
def save_settings(self):
|
def save_settings(self):
|
||||||
""" Save settings to disk. """
|
""" Save settings to disk. """
|
||||||
@@ -415,7 +415,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
|
|||||||
encrypt_methods[self.encryption_combo.get_focus()[1]]['type'])
|
encrypt_methods[self.encryption_combo.get_focus()[1]]['type'])
|
||||||
self.set_net_prop("encryption_enabled", True)
|
self.set_net_prop("encryption_enabled", True)
|
||||||
# Make sure all required fields are filled in.
|
# Make sure all required fields are filled in.
|
||||||
for entry_info in encrypt_info.itervalues():
|
for entry_info in encrypt_info.values():
|
||||||
if entry_info[0].get_edit_text() == "" \
|
if entry_info[0].get_edit_text() == "" \
|
||||||
and entry_info[1] == 'required':
|
and entry_info[1] == 'required':
|
||||||
error(
|
error(
|
||||||
@@ -428,7 +428,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
for entry_key, entry_info in encrypt_info.iteritems():
|
for entry_key, entry_info in encrypt_info.items():
|
||||||
self.set_net_prop(entry_key, noneToString(entry_info[0].
|
self.set_net_prop(entry_key, noneToString(entry_info[0].
|
||||||
get_edit_text()))
|
get_edit_text()))
|
||||||
else:
|
else:
|
||||||
@@ -584,7 +584,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
|
|||||||
bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname'))
|
bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname'))
|
||||||
)
|
)
|
||||||
self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state())
|
self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state())
|
||||||
self.dhcp_h.set_edit_text(unicode(dhcphname))
|
self.dhcp_h.set_edit_text(str(dhcphname))
|
||||||
|
|
||||||
def set_net_prop(self, option, value):
|
def set_net_prop(self, option, value):
|
||||||
""" Sets the given option to the given value for this network. """
|
""" Sets the given option to the given value for this network. """
|
||||||
@@ -606,7 +606,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
|
|||||||
encrypt_methods[self.encryption_combo.get_focus()[1]]['type']
|
encrypt_methods[self.encryption_combo.get_focus()[1]]['type']
|
||||||
)
|
)
|
||||||
# Make sure all required fields are filled in.
|
# Make sure all required fields are filled in.
|
||||||
for entry_info in encrypt_info.itervalues():
|
for entry_info in encrypt_info.values():
|
||||||
if entry_info[0].get_edit_text() == "" \
|
if entry_info[0].get_edit_text() == "" \
|
||||||
and entry_info[1] == 'required':
|
and entry_info[1] == 'required':
|
||||||
error(
|
error(
|
||||||
@@ -619,7 +619,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
for entry_key, entry_info in encrypt_info.iteritems():
|
for entry_key, entry_info in encrypt_info.items():
|
||||||
self.set_net_prop(entry_key, noneToString(entry_info[0].
|
self.set_net_prop(entry_key, noneToString(entry_info[0].
|
||||||
get_edit_text()))
|
get_edit_text()))
|
||||||
elif not self.encryption_chkbox.get_state() and \
|
elif not self.encryption_chkbox.get_state() and \
|
||||||
|
|||||||
@@ -267,8 +267,8 @@ class PrefsDialog(urwid.WidgetWrap):
|
|||||||
""" Load settings to be used in the dialog. """
|
""" Load settings to be used in the dialog. """
|
||||||
### General Settings
|
### General Settings
|
||||||
# ComboBox does not like dbus.Strings as text markups. My fault. :/
|
# ComboBox does not like dbus.Strings as text markups. My fault. :/
|
||||||
wless_iface = unicode(daemon.GetWirelessInterface())
|
wless_iface = str(daemon.GetWirelessInterface())
|
||||||
wired_iface = unicode(daemon.GetWiredInterface())
|
wired_iface = str(daemon.GetWiredInterface())
|
||||||
self.wless_edit.set_edit_text(wless_iface)
|
self.wless_edit.set_edit_text(wless_iface)
|
||||||
self.wired_edit.set_edit_text(wired_iface)
|
self.wired_edit.set_edit_text(wired_iface)
|
||||||
|
|
||||||
@@ -312,7 +312,7 @@ class PrefsDialog(urwid.WidgetWrap):
|
|||||||
self.wpadrivers.append("ralink_legacy")
|
self.wpadrivers.append("ralink_legacy")
|
||||||
self.wpadrivers.append('none')
|
self.wpadrivers.append('none')
|
||||||
# Same as above with the dbus.String
|
# Same as above with the dbus.String
|
||||||
self.thedrivers = [unicode(w) for w in self.wpadrivers]
|
self.thedrivers = [str(w) for w in self.wpadrivers]
|
||||||
self.wpa_cbox.set_list(self.thedrivers)
|
self.wpa_cbox.set_list(self.thedrivers)
|
||||||
|
|
||||||
# Pick where to begin first:
|
# Pick where to begin first:
|
||||||
@@ -323,7 +323,7 @@ class PrefsDialog(urwid.WidgetWrap):
|
|||||||
pass # It defaults to 0 anyway (I hope)
|
pass # It defaults to 0 anyway (I hope)
|
||||||
|
|
||||||
self.backends = daemon.GetBackendList()
|
self.backends = daemon.GetBackendList()
|
||||||
self.thebackends = [unicode(w) for w in self.backends]
|
self.thebackends = [str(w) for w in self.backends]
|
||||||
self.backend_cbox.set_list(self.thebackends)
|
self.backend_cbox.set_list(self.thebackends)
|
||||||
cur_backend = daemon.GetSavedBackend()
|
cur_backend = daemon.GetSavedBackend()
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -99,15 +99,15 @@ def wrap_exceptions(func):
|
|||||||
#gobject.source_remove(redraw_tag)
|
#gobject.source_remove(redraw_tag)
|
||||||
loop.quit()
|
loop.quit()
|
||||||
ui.stop()
|
ui.stop()
|
||||||
print >> sys.stderr, "\n" + _('Terminated by user')
|
print("\n" + _('Terminated by user'), file=sys.stderr)
|
||||||
#raise
|
#raise
|
||||||
except DBusException:
|
except DBusException:
|
||||||
loop.quit()
|
loop.quit()
|
||||||
ui.stop()
|
ui.stop()
|
||||||
print >> sys.stderr, "\n" + _('DBus failure! '
|
print("\n" + _('DBus failure! '
|
||||||
'This is most likely caused by the wicd daemon '
|
'This is most likely caused by the wicd daemon '
|
||||||
'stopping while wicd-curses is running. '
|
'stopping while wicd-curses is running. '
|
||||||
'Please restart the daemon, and then restart wicd-curses.')
|
'Please restart the daemon, and then restart wicd-curses.'), file=sys.stderr)
|
||||||
raise
|
raise
|
||||||
except:
|
except:
|
||||||
# Quit the loop
|
# Quit the loop
|
||||||
@@ -231,7 +231,7 @@ def help_dialog(body):
|
|||||||
textT = urwid.Text(('header', _('wicd-curses help')), 'right')
|
textT = urwid.Text(('header', _('wicd-curses help')), 'right')
|
||||||
textSH = urwid.Text([
|
textSH = urwid.Text([
|
||||||
'This is ', ('blue', 'wicd-curses-' + CURSES_REV),
|
'This is ', ('blue', 'wicd-curses-' + CURSES_REV),
|
||||||
' using wicd ', unicode(daemon.Hello()), '\n'
|
' using wicd ', str(daemon.Hello()), '\n'
|
||||||
])
|
])
|
||||||
|
|
||||||
textH = urwid.Text([
|
textH = urwid.Text([
|
||||||
@@ -517,7 +517,7 @@ class WiredComboBox(ComboBox):
|
|||||||
dialog = InputDialog(
|
dialog = InputDialog(
|
||||||
('header', _('Rename wired profile')),
|
('header', _('Rename wired profile')),
|
||||||
7, 30,
|
7, 30,
|
||||||
edit_text=unicode(self.get_selected_profile())
|
edit_text=str(self.get_selected_profile())
|
||||||
)
|
)
|
||||||
exitcode, name = dialog.run(ui, self.parent)
|
exitcode, name = dialog.run(ui, self.parent)
|
||||||
if exitcode == 0:
|
if exitcode == 0:
|
||||||
@@ -1259,8 +1259,7 @@ def setup_dbus(force=True):
|
|||||||
try:
|
try:
|
||||||
dbusmanager.connect_to_dbus()
|
dbusmanager.connect_to_dbus()
|
||||||
except DBusException:
|
except DBusException:
|
||||||
print >> sys.stderr, \
|
print(_("Can't connect to the daemon, trying to start it automatically..."), file=sys.stderr)
|
||||||
_("Can't connect to the daemon, trying to start it automatically...")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
bus = dbusmanager.get_bus()
|
bus = dbusmanager.get_bus()
|
||||||
@@ -1269,12 +1268,11 @@ def setup_dbus(force=True):
|
|||||||
wireless = dbus_ifaces['wireless']
|
wireless = dbus_ifaces['wireless']
|
||||||
wired = dbus_ifaces['wired']
|
wired = dbus_ifaces['wired']
|
||||||
except DBusException:
|
except DBusException:
|
||||||
print >> sys.stderr, \
|
print(_("Can't automatically start the daemon, this error is fatal..."), file=sys.stderr)
|
||||||
_("Can't automatically start the daemon, this error is fatal...")
|
|
||||||
|
|
||||||
if not daemon:
|
if not daemon:
|
||||||
print 'Error connecting to wicd via D-Bus. ' \
|
print('Error connecting to wicd via D-Bus. ' \
|
||||||
'Please make sure the wicd service is running.'
|
'Please make sure the wicd service is running.')
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
netentry_curses.dbus_init(dbus_ifaces)
|
netentry_curses.dbus_init(dbus_ifaces)
|
||||||
@@ -1292,11 +1290,11 @@ if __name__ == '__main__':
|
|||||||
(CURSES_REV, daemon.Hello()),
|
(CURSES_REV, daemon.Hello()),
|
||||||
prog="wicd-curses"
|
prog="wicd-curses"
|
||||||
)
|
)
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
if "DBus.Error.AccessDenied" in e.get_dbus_name():
|
if "DBus.Error.AccessDenied" in e.get_dbus_name():
|
||||||
print _('ERROR: wicd-curses was denied access to the wicd daemon: '
|
print(_('ERROR: wicd-curses was denied access to the wicd daemon: '
|
||||||
'please check that your user is in the "$A" group.'). \
|
'please check that your user is in the "$A" group.'). \
|
||||||
replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m')
|
replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m'))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ def write_scripts(network, network_type, script_info):
|
|||||||
def main (argv):
|
def main (argv):
|
||||||
""" Runs the script configuration dialog. """
|
""" Runs the script configuration dialog. """
|
||||||
if len(argv) < 2:
|
if len(argv) < 2:
|
||||||
print 'Network id to configure is missing, aborting.'
|
print('Network id to configure is missing, aborting.')
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
network = argv[1]
|
network = argv[1]
|
||||||
@@ -171,6 +171,6 @@ def main (argv):
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if os.getuid() != 0:
|
if os.getuid() != 0:
|
||||||
print "Root privileges are required to configure scripts. Exiting."
|
print("Root privileges are required to configure scripts. Exiting.")
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
main(sys.argv)
|
main(sys.argv)
|
||||||
|
|||||||
24
gtk/gui.py
24
gtk/gui.py
@@ -56,11 +56,11 @@ def setup_dbus(force=True):
|
|||||||
dbusmanager.connect_to_dbus()
|
dbusmanager.connect_to_dbus()
|
||||||
except DBusException:
|
except DBusException:
|
||||||
if force:
|
if force:
|
||||||
print "Can't connect to the daemon, ' + \
|
print("Can't connect to the daemon, ' + \
|
||||||
'trying to start it automatically..."
|
'trying to start it automatically...")
|
||||||
if not misc.PromptToStartDaemon():
|
if not misc.PromptToStartDaemon():
|
||||||
print "Failed to find a graphical sudo program, ' + \
|
print("Failed to find a graphical sudo program, ' + \
|
||||||
'cannot continue."
|
'cannot continue.")
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
dbusmanager.connect_to_dbus()
|
dbusmanager.connect_to_dbus()
|
||||||
@@ -91,7 +91,7 @@ def handle_no_dbus(from_tray=False):
|
|||||||
DBUS_AVAIL = False
|
DBUS_AVAIL = False
|
||||||
if from_tray:
|
if from_tray:
|
||||||
return False
|
return False
|
||||||
print "Wicd daemon is shutting down!"
|
print("Wicd daemon is shutting down!")
|
||||||
error(
|
error(
|
||||||
None,
|
None,
|
||||||
_('The wicd daemon has shut down. The UI will not function '
|
_('The wicd daemon has shut down. The UI will not function '
|
||||||
@@ -146,14 +146,14 @@ class WiredProfileChooser:
|
|||||||
wired_net_entry.profile_help.hide()
|
wired_net_entry.profile_help.hide()
|
||||||
if wired_net_entry.profile_list is not None:
|
if wired_net_entry.profile_list is not None:
|
||||||
wired_profiles.set_active(0)
|
wired_profiles.set_active(0)
|
||||||
print "wired profiles found"
|
print("wired profiles found")
|
||||||
else:
|
else:
|
||||||
print "no wired profiles found"
|
print("no wired profiles found")
|
||||||
wired_net_entry.profile_help.show()
|
wired_net_entry.profile_help.show()
|
||||||
|
|
||||||
response = dialog.run()
|
response = dialog.run()
|
||||||
if response == 1:
|
if response == 1:
|
||||||
print 'reading profile ', wired_profiles.get_active_text()
|
print('reading profile ', wired_profiles.get_active_text())
|
||||||
wired.ReadWiredNetworkProfile(wired_profiles.get_active_text())
|
wired.ReadWiredNetworkProfile(wired_profiles.get_active_text())
|
||||||
wired.ConnectWired()
|
wired.ConnectWired()
|
||||||
else:
|
else:
|
||||||
@@ -282,7 +282,7 @@ class appGui(object):
|
|||||||
|
|
||||||
def create_adhoc_network(self, widget=None):
|
def create_adhoc_network(self, widget=None):
|
||||||
""" Shows a dialog that creates a new adhoc network. """
|
""" Shows a dialog that creates a new adhoc network. """
|
||||||
print "Starting the Ad-Hoc Network Creation Process..."
|
print("Starting the Ad-Hoc Network Creation Process...")
|
||||||
dialog = gtk.Dialog(
|
dialog = gtk.Dialog(
|
||||||
title=_('Create an Ad-Hoc Network'),
|
title=_('Create an Ad-Hoc Network'),
|
||||||
flags=gtk.DIALOG_MODAL,
|
flags=gtk.DIALOG_MODAL,
|
||||||
@@ -695,7 +695,7 @@ class appGui(object):
|
|||||||
wireless.SetHiddenNetworkESSID(noneToString(hidden))
|
wireless.SetHiddenNetworkESSID(noneToString(hidden))
|
||||||
self.refresh_clicked()
|
self.refresh_clicked()
|
||||||
return
|
return
|
||||||
print "refreshing..."
|
print("refreshing...")
|
||||||
self.network_list.set_sensitive(False)
|
self.network_list.set_sensitive(False)
|
||||||
self._remove_items_from_vbox(self.network_list)
|
self._remove_items_from_vbox(self.network_list)
|
||||||
self.wait_for_events()
|
self.wait_for_events()
|
||||||
@@ -707,7 +707,7 @@ class appGui(object):
|
|||||||
if num_networks > 0:
|
if num_networks > 0:
|
||||||
skip_never_connect = not daemon.GetShowNeverConnect()
|
skip_never_connect = not daemon.GetShowNeverConnect()
|
||||||
instruct_label.show()
|
instruct_label.show()
|
||||||
for x in xrange(0, num_networks):
|
for x in range(0, num_networks):
|
||||||
if skip_never_connect and \
|
if skip_never_connect and \
|
||||||
misc.to_bool(get_wireless_prop(x, 'never')):
|
misc.to_bool(get_wireless_prop(x, 'never')):
|
||||||
continue
|
continue
|
||||||
@@ -821,7 +821,7 @@ class appGui(object):
|
|||||||
# Make sure no entries are left blank
|
# Make sure no entries are left blank
|
||||||
if entry.chkbox_encryption.get_active():
|
if entry.chkbox_encryption.get_active():
|
||||||
encryption_info = entry.encryption_info
|
encryption_info = entry.encryption_info
|
||||||
for entry_info in encryption_info.itervalues():
|
for entry_info in encryption_info.values():
|
||||||
if entry_info[0].entry.get_text() == "" and \
|
if entry_info[0].entry.get_text() == "" and \
|
||||||
entry_info[1] == 'required':
|
entry_info[1] == 'required':
|
||||||
error(
|
error(
|
||||||
|
|||||||
@@ -25,16 +25,16 @@ HAS_NOTIFY = True
|
|||||||
try:
|
try:
|
||||||
import pynotify
|
import pynotify
|
||||||
if not pynotify.init("Wicd"):
|
if not pynotify.init("Wicd"):
|
||||||
print 'Could not initalize pynotify'
|
print('Could not initalize pynotify')
|
||||||
HAS_NOTIFY = False
|
HAS_NOTIFY = False
|
||||||
except ImportError:
|
except ImportError:
|
||||||
print "Importing pynotify failed, notifications disabled."
|
print("Importing pynotify failed, notifications disabled.")
|
||||||
HAS_NOTIFY = False
|
HAS_NOTIFY = False
|
||||||
|
|
||||||
print "Has notifications support", HAS_NOTIFY
|
print("Has notifications support", HAS_NOTIFY)
|
||||||
|
|
||||||
if wpath.no_use_notifications:
|
if wpath.no_use_notifications:
|
||||||
print 'Notifications disabled during setup.py configure'
|
print('Notifications disabled during setup.py configure')
|
||||||
|
|
||||||
|
|
||||||
def can_use_notify():
|
def can_use_notify():
|
||||||
|
|||||||
@@ -465,14 +465,14 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
|
|||||||
self.chkbox_encryption.get_active()
|
self.chkbox_encryption.get_active()
|
||||||
)
|
)
|
||||||
if self.chkbox_encryption.get_active():
|
if self.chkbox_encryption.get_active():
|
||||||
print "setting encryption info..."
|
print("setting encryption info...")
|
||||||
encrypt_methods = self.encrypt_types
|
encrypt_methods = self.encrypt_types
|
||||||
self.set_net_prop(
|
self.set_net_prop(
|
||||||
"enctype",
|
"enctype",
|
||||||
encrypt_methods[self.combo_encryption.get_active()]['type']
|
encrypt_methods[self.combo_encryption.get_active()]['type']
|
||||||
)
|
)
|
||||||
# Make sure all required fields are filled in.
|
# Make sure all required fields are filled in.
|
||||||
for entry_info in encrypt_info.itervalues():
|
for entry_info in encrypt_info.values():
|
||||||
if entry_info[0].entry.get_text() == "" and \
|
if entry_info[0].entry.get_text() == "" and \
|
||||||
entry_info[1] == 'required':
|
entry_info[1] == 'required':
|
||||||
error(
|
error(
|
||||||
@@ -484,11 +484,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
# Now save all the entries.
|
# Now save all the entries.
|
||||||
for entry_key, entry_info in encrypt_info.iteritems():
|
for entry_key, entry_info in encrypt_info.items():
|
||||||
self.set_net_prop(entry_key,
|
self.set_net_prop(entry_key,
|
||||||
noneToString(entry_info[0].entry.get_text()))
|
noneToString(entry_info[0].entry.get_text()))
|
||||||
else:
|
else:
|
||||||
print "no encryption specified..."
|
print("no encryption specified...")
|
||||||
self.set_net_prop("enctype", "None")
|
self.set_net_prop("enctype", "None")
|
||||||
AdvancedSettingsDialog.save_settings(self)
|
AdvancedSettingsDialog.save_settings(self)
|
||||||
wired.SaveWiredNetworkProfile(self.prof_name)
|
wired.SaveWiredNetworkProfile(self.prof_name)
|
||||||
@@ -682,14 +682,14 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
|
|||||||
# Check encryption info
|
# Check encryption info
|
||||||
encrypt_info = self.encryption_info
|
encrypt_info = self.encryption_info
|
||||||
if self.chkbox_encryption.get_active():
|
if self.chkbox_encryption.get_active():
|
||||||
print "setting encryption info..."
|
print("setting encryption info...")
|
||||||
encrypt_methods = self.encrypt_types
|
encrypt_methods = self.encrypt_types
|
||||||
self.set_net_prop(
|
self.set_net_prop(
|
||||||
"enctype",
|
"enctype",
|
||||||
encrypt_methods[self.combo_encryption.get_active()]['type']
|
encrypt_methods[self.combo_encryption.get_active()]['type']
|
||||||
)
|
)
|
||||||
# Make sure all required fields are filled in.
|
# Make sure all required fields are filled in.
|
||||||
for entry_info in encrypt_info.itervalues():
|
for entry_info in encrypt_info.values():
|
||||||
if entry_info[0].entry.get_text() == "" and \
|
if entry_info[0].entry.get_text() == "" and \
|
||||||
entry_info[1] == 'required':
|
entry_info[1] == 'required':
|
||||||
error(
|
error(
|
||||||
@@ -701,7 +701,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
# Now save all the entries.
|
# Now save all the entries.
|
||||||
for entry_key, entry_info in encrypt_info.iteritems():
|
for entry_key, entry_info in encrypt_info.items():
|
||||||
self.set_net_prop(entry_key,
|
self.set_net_prop(entry_key,
|
||||||
noneToString(entry_info[0].entry.get_text()))
|
noneToString(entry_info[0].entry.get_text()))
|
||||||
elif not self.chkbox_encryption.get_active() and \
|
elif not self.chkbox_encryption.get_active() and \
|
||||||
@@ -710,7 +710,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
|
|||||||
error(self, _('This network requires encryption to be enabled.'))
|
error(self, _('This network requires encryption to be enabled.'))
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
print "no encryption specified..."
|
print("no encryption specified...")
|
||||||
self.set_net_prop("enctype", "None")
|
self.set_net_prop("enctype", "None")
|
||||||
AdvancedSettingsDialog.save_settings(self)
|
AdvancedSettingsDialog.save_settings(self)
|
||||||
|
|
||||||
@@ -861,7 +861,7 @@ class WiredNetworkEntry(NetworkEntry):
|
|||||||
starting_index = x
|
starting_index = x
|
||||||
self.combo_profile_names.set_active(starting_index)
|
self.combo_profile_names.set_active(starting_index)
|
||||||
else:
|
else:
|
||||||
print "no wired profiles found"
|
print("no wired profiles found")
|
||||||
self.profile_help.show()
|
self.profile_help.show()
|
||||||
|
|
||||||
self.advanced_dialog = \
|
self.advanced_dialog = \
|
||||||
@@ -942,7 +942,7 @@ class WiredNetworkEntry(NetworkEntry):
|
|||||||
|
|
||||||
def remove_profile(self, widget):
|
def remove_profile(self, widget):
|
||||||
""" Remove a profile from the profile list. """
|
""" Remove a profile from the profile list. """
|
||||||
print "removing profile"
|
print("removing profile")
|
||||||
profile_name = self.combo_profile_names.get_active_text()
|
profile_name = self.combo_profile_names.get_active_text()
|
||||||
wired.DeleteWiredNetworkProfile(profile_name)
|
wired.DeleteWiredNetworkProfile(profile_name)
|
||||||
self.combo_profile_names.remove_text(self.combo_profile_names.
|
self.combo_profile_names.remove_text(self.combo_profile_names.
|
||||||
@@ -1010,7 +1010,7 @@ class WirelessNetworkEntry(NetworkEntry):
|
|||||||
self.lbl_encryption = GreyLabel()
|
self.lbl_encryption = GreyLabel()
|
||||||
self.lbl_channel = GreyLabel()
|
self.lbl_channel = GreyLabel()
|
||||||
|
|
||||||
print "ESSID : " + self.essid
|
print("ESSID : " + self.essid)
|
||||||
self.chkbox_autoconnect = gtk.CheckButton(
|
self.chkbox_autoconnect = gtk.CheckButton(
|
||||||
_('Automatically connect to this network'))
|
_('Automatically connect to this network'))
|
||||||
self.chkbox_neverconnect = gtk.CheckButton(
|
self.chkbox_neverconnect = gtk.CheckButton(
|
||||||
|
|||||||
@@ -80,8 +80,8 @@ if not hasattr(gtk, "StatusIcon"):
|
|||||||
import egg.trayicon
|
import egg.trayicon
|
||||||
USE_EGG = True
|
USE_EGG = True
|
||||||
except ImportError:
|
except ImportError:
|
||||||
print 'Unable to load tray icon: Missing both egg.trayicon and ' + \
|
print('Unable to load tray icon: Missing both egg.trayicon and ' + \
|
||||||
'gtk.StatusIcon modules.'
|
'gtk.StatusIcon modules.')
|
||||||
ICON_AVAIL = False
|
ICON_AVAIL = False
|
||||||
|
|
||||||
misc.RenameProcess("wicd-client")
|
misc.RenameProcess("wicd-client")
|
||||||
@@ -101,7 +101,7 @@ def catchdbus(func):
|
|||||||
def wrapper(*args, **kwargs):
|
def wrapper(*args, **kwargs):
|
||||||
try:
|
try:
|
||||||
return func(*args, **kwargs)
|
return func(*args, **kwargs)
|
||||||
except DBusException, e:
|
except DBusException as e:
|
||||||
if e.get_dbus_name() is not None and \
|
if e.get_dbus_name() is not None and \
|
||||||
"DBus.Error.AccessDenied" in e.get_dbus_name():
|
"DBus.Error.AccessDenied" in e.get_dbus_name():
|
||||||
error(
|
error(
|
||||||
@@ -114,7 +114,7 @@ def catchdbus(func):
|
|||||||
#raise
|
#raise
|
||||||
raise DBusException(e)
|
raise DBusException(e)
|
||||||
else:
|
else:
|
||||||
print "warning: ignoring exception %s" % e
|
print("warning: ignoring exception %s" % e)
|
||||||
return None
|
return None
|
||||||
wrapper.__name__ = func.__name__
|
wrapper.__name__ = func.__name__
|
||||||
wrapper.__module__ = func.__module__
|
wrapper.__module__ = func.__module__
|
||||||
@@ -162,7 +162,7 @@ class TrayIcon(object):
|
|||||||
self.tr.toggle_wicd_gui()
|
self.tr.toggle_wicd_gui()
|
||||||
self.icon_info = self.TrayConnectionInfo(self, self.tr, animate)
|
self.icon_info = self.TrayConnectionInfo(self, self.tr, animate)
|
||||||
self.tr.icon_info = self.icon_info
|
self.tr.icon_info = self.icon_info
|
||||||
print 'displaytray %s' % displaytray
|
print('displaytray %s' % displaytray)
|
||||||
self.tr.visible(displaytray)
|
self.tr.visible(displaytray)
|
||||||
|
|
||||||
def is_embedded(self):
|
def is_embedded(self):
|
||||||
@@ -263,14 +263,14 @@ class TrayIcon(object):
|
|||||||
self._last_bubble.clear_hints()
|
self._last_bubble.clear_hints()
|
||||||
self._last_bubble.update(title, details, image)
|
self._last_bubble.update(title, details, image)
|
||||||
self._last_bubble.show()
|
self._last_bubble.show()
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
if hasattr(e, 'message') and e.message != '':
|
if hasattr(e, 'message') and e.message != '':
|
||||||
msg = e.message
|
msg = e.message
|
||||||
elif hasattr(e, 'args') and len(e.args) > 0:
|
elif hasattr(e, 'args') and len(e.args) > 0:
|
||||||
msg = e.args[-1]
|
msg = e.args[-1]
|
||||||
else:
|
else:
|
||||||
msg = str(e)
|
msg = str(e)
|
||||||
print "Exception during notification: %s" % msg
|
print("Exception during notification: %s" % msg)
|
||||||
|
|
||||||
self.should_notify = False
|
self.should_notify = False
|
||||||
|
|
||||||
@@ -386,7 +386,7 @@ class TrayIcon(object):
|
|||||||
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
|
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
|
||||||
self.set_not_connected_state(info)
|
self.set_not_connected_state(info)
|
||||||
else:
|
else:
|
||||||
print 'Invalid state returned!!!'
|
print('Invalid state returned!!!')
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -820,7 +820,7 @@ TX:'''))
|
|||||||
|
|
||||||
if num_networks > 0:
|
if num_networks > 0:
|
||||||
skip_never_connect = not daemon.GetShowNeverConnect()
|
skip_never_connect = not daemon.GetShowNeverConnect()
|
||||||
for x in xrange(0, num_networks):
|
for x in range(0, num_networks):
|
||||||
if skip_never_connect and \
|
if skip_never_connect and \
|
||||||
misc.to_bool(get_prop(x,"never")):
|
misc.to_bool(get_prop(x,"never")):
|
||||||
continue
|
continue
|
||||||
@@ -1046,7 +1046,7 @@ TX:'''))
|
|||||||
|
|
||||||
def usage():
|
def usage():
|
||||||
""" Print usage information. """
|
""" Print usage information. """
|
||||||
print """
|
print("""
|
||||||
wicd %s
|
wicd %s
|
||||||
wireless (and wired) connection daemon front-end.
|
wireless (and wired) connection daemon front-end.
|
||||||
|
|
||||||
@@ -1056,19 +1056,19 @@ Arguments:
|
|||||||
\t-h\t--help\t\tPrint this help information.
|
\t-h\t--help\t\tPrint this help information.
|
||||||
\t-a\t--no-animate\tRun the tray without network traffic tray animations.
|
\t-a\t--no-animate\tRun the tray without network traffic tray animations.
|
||||||
\t-o\t--only-notifications\tDon't display anything except notifications.
|
\t-o\t--only-notifications\tDon't display anything except notifications.
|
||||||
""" % wpath.version
|
""" % wpath.version)
|
||||||
|
|
||||||
|
|
||||||
def setup_dbus(force=True):
|
def setup_dbus(force=True):
|
||||||
""" Initialize DBus. """
|
""" Initialize DBus. """
|
||||||
global daemon, wireless, wired, DBUS_AVAIL, lost_dbus_id
|
global daemon, wireless, wired, DBUS_AVAIL, lost_dbus_id
|
||||||
print "Connecting to daemon..."
|
print("Connecting to daemon...")
|
||||||
try:
|
try:
|
||||||
dbusmanager.connect_to_dbus()
|
dbusmanager.connect_to_dbus()
|
||||||
except DBusException:
|
except DBusException:
|
||||||
if force:
|
if force:
|
||||||
print "Can't connect to the daemon, trying to start it " + \
|
print("Can't connect to the daemon, trying to start it " + \
|
||||||
"automatically..."
|
"automatically...")
|
||||||
misc.PromptToStartDaemon()
|
misc.PromptToStartDaemon()
|
||||||
try:
|
try:
|
||||||
dbusmanager.connect_to_dbus()
|
dbusmanager.connect_to_dbus()
|
||||||
@@ -1089,7 +1089,7 @@ def setup_dbus(force=True):
|
|||||||
wireless = dbus_ifaces['wireless']
|
wireless = dbus_ifaces['wireless']
|
||||||
wired = dbus_ifaces['wired']
|
wired = dbus_ifaces['wired']
|
||||||
DBUS_AVAIL = True
|
DBUS_AVAIL = True
|
||||||
print "Connected."
|
print("Connected.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -1107,7 +1107,7 @@ def handle_no_dbus():
|
|||||||
global DBUS_AVAIL, lost_dbus_id
|
global DBUS_AVAIL, lost_dbus_id
|
||||||
DBUS_AVAIL = False
|
DBUS_AVAIL = False
|
||||||
gui.handle_no_dbus(from_tray=True)
|
gui.handle_no_dbus(from_tray=True)
|
||||||
print "Wicd daemon is shutting down!"
|
print("Wicd daemon is shutting down!")
|
||||||
lost_dbus_id = misc.timeout_add(5,
|
lost_dbus_id = misc.timeout_add(5,
|
||||||
lambda: error(None,
|
lambda: error(None,
|
||||||
_('The wicd daemon has shut down. The UI will not function '
|
_('The wicd daemon has shut down. The UI will not function '
|
||||||
@@ -1151,14 +1151,14 @@ def main(argv):
|
|||||||
elif opt in ('-a', '--no-animate'):
|
elif opt in ('-a', '--no-animate'):
|
||||||
animate = False
|
animate = False
|
||||||
elif opt in ('-o', '--only-notifications'):
|
elif opt in ('-o', '--only-notifications'):
|
||||||
print "only displaying notifications"
|
print("only displaying notifications")
|
||||||
use_tray = False
|
use_tray = False
|
||||||
display_app = False
|
display_app = False
|
||||||
else:
|
else:
|
||||||
usage()
|
usage()
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|
||||||
print 'Loading...'
|
print('Loading...')
|
||||||
setup_dbus()
|
setup_dbus()
|
||||||
atexit.register(on_exit)
|
atexit.register(on_exit)
|
||||||
|
|
||||||
@@ -1195,7 +1195,7 @@ def main(argv):
|
|||||||
)
|
)
|
||||||
bus.add_signal_receiver(lambda: setup_dbus(force=False), "DaemonStarting",
|
bus.add_signal_receiver(lambda: setup_dbus(force=False), "DaemonStarting",
|
||||||
"org.wicd.daemon")
|
"org.wicd.daemon")
|
||||||
print 'Done loading.'
|
print('Done loading.')
|
||||||
mainloop = gobject.MainLoop()
|
mainloop = gobject.MainLoop()
|
||||||
mainloop.run()
|
mainloop.run()
|
||||||
|
|
||||||
|
|||||||
66
setup.py
66
setup.py
@@ -51,9 +51,9 @@ try:
|
|||||||
pass
|
pass
|
||||||
import vcsinfo
|
import vcsinfo
|
||||||
REVISION_NUM = vcsinfo.version_info['revno']
|
REVISION_NUM = vcsinfo.version_info['revno']
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
print 'failed to find revision number:'
|
print('failed to find revision number:')
|
||||||
print e
|
print(e)
|
||||||
|
|
||||||
class build(_build):
|
class build(_build):
|
||||||
sub_commands = _build.sub_commands + [('compile_translations', None)]
|
sub_commands = _build.sub_commands + [('compile_translations', None)]
|
||||||
@@ -216,10 +216,10 @@ class configure(Command):
|
|||||||
self.ddistro = 'FAIL'
|
self.ddistro = 'FAIL'
|
||||||
#self.no_install_init = True
|
#self.no_install_init = True
|
||||||
#self.distro_detect_failed = True
|
#self.distro_detect_failed = True
|
||||||
print 'WARNING: Unable to detect the distribution in use. ' + \
|
print('WARNING: Unable to detect the distribution in use. ' + \
|
||||||
'If you have specified --distro or --init and --initfile, configure will continue. ' + \
|
'If you have specified --distro or --init and --initfile, configure will continue. ' + \
|
||||||
'Please report this warning, along with the name of your ' + \
|
'Please report this warning, along with the name of your ' + \
|
||||||
'distribution, to the wicd developers.'
|
'distribution, to the wicd developers.')
|
||||||
|
|
||||||
# Try to get the pm-utils sleep hooks directory from pkg-config and
|
# Try to get the pm-utils sleep hooks directory from pkg-config and
|
||||||
# the kde prefix from kde-config
|
# the kde prefix from kde-config
|
||||||
@@ -276,7 +276,7 @@ class configure(Command):
|
|||||||
self.logperms = '0600'
|
self.logperms = '0600'
|
||||||
|
|
||||||
def distro_check(self):
|
def distro_check(self):
|
||||||
print "Distro is: " + self.distro
|
print("Distro is: " + self.distro)
|
||||||
if self.distro in ['sles', 'suse']:
|
if self.distro in ['sles', 'suse']:
|
||||||
self.init = '/etc/init.d/'
|
self.init = '/etc/init.d/'
|
||||||
self.initfile = 'init/suse/wicd'
|
self.initfile = 'init/suse/wicd'
|
||||||
@@ -313,11 +313,11 @@ class configure(Command):
|
|||||||
self.initfile = 'init/lunar/wicd'
|
self.initfile = 'init/lunar/wicd'
|
||||||
else :
|
else :
|
||||||
if self.distro == 'auto':
|
if self.distro == 'auto':
|
||||||
print "NOTICE: Automatic distro detection found: " + self.ddistro + ", retrying with that..."
|
print("NOTICE: Automatic distro detection found: " + self.ddistro + ", retrying with that...")
|
||||||
self.distro = self.ddistro
|
self.distro = self.ddistro
|
||||||
self.distro_check()
|
self.distro_check()
|
||||||
else:
|
else:
|
||||||
print "WARNING: Distro detection failed!"
|
print("WARNING: Distro detection failed!")
|
||||||
self.no_install_init = True
|
self.no_install_init = True
|
||||||
self.distro_detect_failed = True
|
self.distro_detect_failed = True
|
||||||
|
|
||||||
@@ -326,8 +326,8 @@ class configure(Command):
|
|||||||
self.distro_check()
|
self.distro_check()
|
||||||
if self.distro_detect_failed and not self.no_install_init and \
|
if self.distro_detect_failed and not self.no_install_init and \
|
||||||
'FAIL' in [self.init, self.initfile]:
|
'FAIL' in [self.init, self.initfile]:
|
||||||
print 'ERROR: Failed to detect distro. Configure cannot continue. ' + \
|
print('ERROR: Failed to detect distro. Configure cannot continue. ' + \
|
||||||
'Please specify --init and --initfile to continue with configuration.'
|
'Please specify --init and --initfile to continue with configuration.')
|
||||||
|
|
||||||
# loop through the argument definitions in user_options
|
# loop through the argument definitions in user_options
|
||||||
for argument in self.user_options:
|
for argument in self.user_options:
|
||||||
@@ -353,26 +353,26 @@ class configure(Command):
|
|||||||
if argument[0].endswith('='):
|
if argument[0].endswith('='):
|
||||||
cur_arg = argument[0][:-1]
|
cur_arg = argument[0][:-1]
|
||||||
cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
|
cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
|
||||||
print "%s is %s" % (cur_arg, cur_arg_value)
|
print("%s is %s" % (cur_arg, cur_arg_value))
|
||||||
values.append((cur_arg, getattr(self, cur_arg.replace('-','_'))))
|
values.append((cur_arg, getattr(self, cur_arg.replace('-','_'))))
|
||||||
else:
|
else:
|
||||||
cur_arg = argument[0]
|
cur_arg = argument[0]
|
||||||
cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
|
cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
|
||||||
print "Found switch %s %s" % (argument, cur_arg_value)
|
print("Found switch %s %s" % (argument, cur_arg_value))
|
||||||
values.append((cur_arg, bool(cur_arg_value)))
|
values.append((cur_arg, bool(cur_arg_value)))
|
||||||
|
|
||||||
print 'Replacing values in template files...'
|
print('Replacing values in template files...')
|
||||||
for item in os.listdir('in'):
|
for item in os.listdir('in'):
|
||||||
if item.endswith('.in'):
|
if item.endswith('.in'):
|
||||||
print 'Replacing values in',item,
|
print('Replacing values in',item, end=' ')
|
||||||
original_name = os.path.join('in',item)
|
original_name = os.path.join('in',item)
|
||||||
item_in = open(original_name, 'r')
|
item_in = open(original_name, 'r')
|
||||||
final_name = item[:-3].replace('=','/')
|
final_name = item[:-3].replace('=','/')
|
||||||
parent_dir = os.path.dirname(final_name)
|
parent_dir = os.path.dirname(final_name)
|
||||||
if parent_dir and not os.path.exists(parent_dir):
|
if parent_dir and not os.path.exists(parent_dir):
|
||||||
print '(mkdir %s)'%parent_dir,
|
print('(mkdir %s)'%parent_dir, end=' ')
|
||||||
os.makedirs(parent_dir)
|
os.makedirs(parent_dir)
|
||||||
print final_name
|
print(final_name)
|
||||||
item_out = open(final_name, 'w')
|
item_out = open(final_name, 'w')
|
||||||
for line in item_in.readlines():
|
for line in item_in.readlines():
|
||||||
for item, value in values:
|
for item, value in values:
|
||||||
@@ -403,19 +403,19 @@ class clear_generated(Command):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
print 'Removing completed template files...'
|
print('Removing completed template files...')
|
||||||
for item in os.listdir('in'):
|
for item in os.listdir('in'):
|
||||||
if item.endswith('.in'):
|
if item.endswith('.in'):
|
||||||
print 'Removing completed',item,
|
print('Removing completed',item, end=' ')
|
||||||
original_name = os.path.join('in',item)
|
original_name = os.path.join('in',item)
|
||||||
final_name = item[:-3].replace('=','/')
|
final_name = item[:-3].replace('=','/')
|
||||||
print final_name, '...',
|
print(final_name, '...', end=' ')
|
||||||
if os.path.exists(final_name):
|
if os.path.exists(final_name):
|
||||||
os.remove(final_name)
|
os.remove(final_name)
|
||||||
print 'Removed.'
|
print('Removed.')
|
||||||
else:
|
else:
|
||||||
print 'Does not exist.'
|
print('Does not exist.')
|
||||||
print 'Removing compiled translation files...'
|
print('Removing compiled translation files...')
|
||||||
if os.path.exists('translations'):
|
if os.path.exists('translations'):
|
||||||
shutil.rmtree('translations/')
|
shutil.rmtree('translations/')
|
||||||
os.makedirs('translations/')
|
os.makedirs('translations/')
|
||||||
@@ -428,7 +428,7 @@ class install(_install):
|
|||||||
self.run_command('build')
|
self.run_command('build')
|
||||||
import wpath
|
import wpath
|
||||||
|
|
||||||
print "Using init file",(wpath.init, wpath.initfile)
|
print("Using init file",(wpath.init, wpath.initfile))
|
||||||
data.extend([
|
data.extend([
|
||||||
(wpath.dbus, ['other/wicd.conf']),
|
(wpath.dbus, ['other/wicd.conf']),
|
||||||
(wpath.dbus_service, ['other/org.wicd.daemon.service']),
|
(wpath.dbus_service, ['other/org.wicd.daemon.service']),
|
||||||
@@ -536,15 +536,15 @@ class install(_install):
|
|||||||
data.append((wpath.suspend, ['other/50-wicd-suspend.sh']))
|
data.append((wpath.suspend, ['other/50-wicd-suspend.sh']))
|
||||||
if not wpath.no_install_pmutils:
|
if not wpath.no_install_pmutils:
|
||||||
data.append((wpath.pmutils, ['other/55wicd']))
|
data.append((wpath.pmutils, ['other/55wicd']))
|
||||||
print 'Using pid path', os.path.basename(wpath.pidfile)
|
print('Using pid path', os.path.basename(wpath.pidfile))
|
||||||
if not wpath.no_install_i18n:
|
if not wpath.no_install_i18n:
|
||||||
print 'Language support for',
|
print('Language support for', end=' ')
|
||||||
for language in sorted(glob('translations/*')):
|
for language in sorted(glob('translations/*')):
|
||||||
language = language.replace('translations/', '')
|
language = language.replace('translations/', '')
|
||||||
print language,
|
print(language, end=' ')
|
||||||
data.append((wpath.translations + language + '/LC_MESSAGES/',
|
data.append((wpath.translations + language + '/LC_MESSAGES/',
|
||||||
['translations/' + language + '/LC_MESSAGES/wicd.mo']))
|
['translations/' + language + '/LC_MESSAGES/wicd.mo']))
|
||||||
print
|
print()
|
||||||
|
|
||||||
_install.run(self)
|
_install.run(self)
|
||||||
|
|
||||||
@@ -560,9 +560,9 @@ class test(Command):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
print "importing tests"
|
print("importing tests")
|
||||||
import tests
|
import tests
|
||||||
print 'running tests'
|
print('running tests')
|
||||||
tests.run_tests()
|
tests.run_tests()
|
||||||
|
|
||||||
class update_message_catalog(Command):
|
class update_message_catalog(Command):
|
||||||
@@ -633,7 +633,7 @@ class compile_translations(Command):
|
|||||||
returncode = msgfmt.wait() # let it finish, and get the exit code
|
returncode = msgfmt.wait() # let it finish, and get the exit code
|
||||||
output = msgfmt.stderr.readline().strip()
|
output = msgfmt.stderr.readline().strip()
|
||||||
if len(output) == 0 or returncode != 0:
|
if len(output) == 0 or returncode != 0:
|
||||||
print len(output), returncode
|
print(len(output), returncode)
|
||||||
raise ValueError
|
raise ValueError
|
||||||
else:
|
else:
|
||||||
m = re.match('(\d+) translated messages(?:, (\d+) fuzzy translation)?(?:, (\d+) untranslated messages)?.', output)
|
m = re.match('(\d+) translated messages(?:, (\d+) fuzzy translation)?(?:, (\d+) untranslated messages)?.', output)
|
||||||
@@ -646,11 +646,11 @@ class compile_translations(Command):
|
|||||||
if completeness >= self.threshold:
|
if completeness >= self.threshold:
|
||||||
compile_po = True
|
compile_po = True
|
||||||
else:
|
else:
|
||||||
print 'Disabled %s (%s%% < %s%%).' % \
|
print('Disabled %s (%s%% < %s%%).' % \
|
||||||
(lang, completeness*100, self.threshold*100)
|
(lang, completeness*100, self.threshold*100))
|
||||||
continue
|
continue
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
print 'ARGH'
|
print('ARGH')
|
||||||
|
|
||||||
if compile_po:
|
if compile_po:
|
||||||
os.makedirs('translations/' + lang + '/LC_MESSAGES/')
|
os.makedirs('translations/' + lang + '/LC_MESSAGES/')
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ def run_tests():
|
|||||||
import unittest
|
import unittest
|
||||||
test_suite = unittest.TestSuite()
|
test_suite = unittest.TestSuite()
|
||||||
|
|
||||||
import testwnettools
|
from . import testwnettools
|
||||||
test_suite.addTest(testwnettools.suite())
|
test_suite.addTest(testwnettools.suite())
|
||||||
|
|
||||||
import testmisc
|
from . import testmisc
|
||||||
test_suite.addTest(testmisc.suite())
|
test_suite.addTest(testmisc.suite())
|
||||||
|
|
||||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from wicd import misc
|
|||||||
class TestMisc(unittest.TestCase):
|
class TestMisc(unittest.TestCase):
|
||||||
def test_misc_run(self):
|
def test_misc_run(self):
|
||||||
output = misc.Run(['echo', 'hi']).strip()
|
output = misc.Run(['echo', 'hi']).strip()
|
||||||
self.assertEquals('hi', output)
|
self.assertEqual('hi', output)
|
||||||
|
|
||||||
def test_valid_ip_1(self):
|
def test_valid_ip_1(self):
|
||||||
self.assertTrue(misc.IsValidIP('0.0.0.0'))
|
self.assertTrue(misc.IsValidIP('0.0.0.0'))
|
||||||
@@ -55,13 +55,13 @@ class TestMisc(unittest.TestCase):
|
|||||||
import re
|
import re
|
||||||
regex = re.compile('.*(ABC.EFG).*')
|
regex = re.compile('.*(ABC.EFG).*')
|
||||||
found = misc.RunRegex(regex, '01234ABCDEFG56789')
|
found = misc.RunRegex(regex, '01234ABCDEFG56789')
|
||||||
self.assertEquals(found, 'ABCDEFG')
|
self.assertEqual(found, 'ABCDEFG')
|
||||||
|
|
||||||
def test_run_invalid_regex(self):
|
def test_run_invalid_regex(self):
|
||||||
import re
|
import re
|
||||||
regex = re.compile('.*(ABC.EFG).*')
|
regex = re.compile('.*(ABC.EFG).*')
|
||||||
found = misc.RunRegex(regex, '01234ABCEDFG56789')
|
found = misc.RunRegex(regex, '01234ABCEDFG56789')
|
||||||
self.assertEquals(found, None)
|
self.assertEqual(found, None)
|
||||||
|
|
||||||
def test_to_boolean_false(self):
|
def test_to_boolean_false(self):
|
||||||
self.assertFalse(misc.to_bool('False'))
|
self.assertFalse(misc.to_bool('False'))
|
||||||
@@ -76,13 +76,13 @@ class TestMisc(unittest.TestCase):
|
|||||||
self.assertTrue(misc.to_bool('1'))
|
self.assertTrue(misc.to_bool('1'))
|
||||||
|
|
||||||
def test_noneify_1(self):
|
def test_noneify_1(self):
|
||||||
self.assertEquals(misc.Noneify('None'), None)
|
self.assertEqual(misc.Noneify('None'), None)
|
||||||
|
|
||||||
def test_noneify_2(self):
|
def test_noneify_2(self):
|
||||||
self.assertEquals(misc.Noneify(''), None)
|
self.assertEqual(misc.Noneify(''), None)
|
||||||
|
|
||||||
def test_noneify_3(self):
|
def test_noneify_3(self):
|
||||||
self.assertEquals(misc.Noneify(None), None)
|
self.assertEqual(misc.Noneify(None), None)
|
||||||
|
|
||||||
def test_noneify_4(self):
|
def test_noneify_4(self):
|
||||||
self.assertFalse(misc.Noneify('False'))
|
self.assertFalse(misc.Noneify('False'))
|
||||||
@@ -103,65 +103,65 @@ class TestMisc(unittest.TestCase):
|
|||||||
self.assertTrue(misc.Noneify(True))
|
self.assertTrue(misc.Noneify(True))
|
||||||
|
|
||||||
def test_noneify_10(self):
|
def test_noneify_10(self):
|
||||||
self.assertEquals(misc.Noneify('randomtext'), 'randomtext')
|
self.assertEqual(misc.Noneify('randomtext'), 'randomtext')
|
||||||
|
|
||||||
def test_noneify_11(self):
|
def test_noneify_11(self):
|
||||||
self.assertEquals(misc.Noneify(5), 5)
|
self.assertEqual(misc.Noneify(5), 5)
|
||||||
|
|
||||||
def test_noneify_12(self):
|
def test_noneify_12(self):
|
||||||
self.assertEquals(misc.Noneify(1, False), 1)
|
self.assertEqual(misc.Noneify(1, False), 1)
|
||||||
|
|
||||||
def test_noneify_13(self):
|
def test_noneify_13(self):
|
||||||
self.assertEquals(misc.Noneify(0, False), 0)
|
self.assertEqual(misc.Noneify(0, False), 0)
|
||||||
|
|
||||||
def test_none_to_string_1(self):
|
def test_none_to_string_1(self):
|
||||||
self.assertEquals(misc.noneToString(None), 'None')
|
self.assertEqual(misc.noneToString(None), 'None')
|
||||||
|
|
||||||
def test_none_to_string_2(self):
|
def test_none_to_string_2(self):
|
||||||
self.assertEquals(misc.noneToString(''), 'None')
|
self.assertEqual(misc.noneToString(''), 'None')
|
||||||
|
|
||||||
def test_none_to_string_3(self):
|
def test_none_to_string_3(self):
|
||||||
self.assertEquals(misc.noneToString(None), 'None')
|
self.assertEqual(misc.noneToString(None), 'None')
|
||||||
|
|
||||||
####################################################################
|
####################################################################
|
||||||
# misc.to_unicode actually converts to utf-8, which is type str #
|
# misc.to_unicode actually converts to utf-8, which is type str #
|
||||||
####################################################################
|
####################################################################
|
||||||
|
|
||||||
def test_to_unicode_1(self):
|
def test_to_unicode_1(self):
|
||||||
self.assertEquals(misc.to_unicode('邪悪'), '邪悪')
|
self.assertEqual(misc.to_unicode('邪悪'), '邪悪')
|
||||||
|
|
||||||
def test_to_unicode_2(self):
|
def test_to_unicode_2(self):
|
||||||
self.assertEquals(misc.to_unicode(u'邪悪'), '邪悪')
|
self.assertEqual(misc.to_unicode('邪悪'), '邪悪')
|
||||||
|
|
||||||
def test_to_unicode_3(self):
|
def test_to_unicode_3(self):
|
||||||
self.assertEquals(misc.to_unicode(u'abcdef'), 'abcdef')
|
self.assertEqual(misc.to_unicode('abcdef'), 'abcdef')
|
||||||
|
|
||||||
def test_to_unicode_4(self):
|
def test_to_unicode_4(self):
|
||||||
self.assertEquals(type(misc.to_unicode('abcdef'.encode('latin-1'))), str)
|
self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), str)
|
||||||
|
|
||||||
def test_to_unicode_5(self):
|
def test_to_unicode_5(self):
|
||||||
self.assertEquals(misc.to_unicode("berkåk"), "berkåk")
|
self.assertEqual(misc.to_unicode("berkåk"), "berkåk")
|
||||||
|
|
||||||
def test_to_unicode_6(self):
|
def test_to_unicode_6(self):
|
||||||
self.assertEquals(misc.to_unicode('berk\xe5k'), "berkåk")
|
self.assertEqual(misc.to_unicode('berk\xe5k'), "berkåk")
|
||||||
|
|
||||||
def test_none_to_blank_string_1(self):
|
def test_none_to_blank_string_1(self):
|
||||||
self.assertEquals(misc.noneToBlankString(None), '')
|
self.assertEqual(misc.noneToBlankString(None), '')
|
||||||
|
|
||||||
def test_none_to_blank_string_2(self):
|
def test_none_to_blank_string_2(self):
|
||||||
self.assertEquals(misc.noneToBlankString('None'), '')
|
self.assertEqual(misc.noneToBlankString('None'), '')
|
||||||
|
|
||||||
def test_string_to_none_1(self):
|
def test_string_to_none_1(self):
|
||||||
self.assertEquals(misc.stringToNone(''), None)
|
self.assertEqual(misc.stringToNone(''), None)
|
||||||
|
|
||||||
def test_string_to_none_2(self):
|
def test_string_to_none_2(self):
|
||||||
self.assertEquals(misc.stringToNone('None'), None)
|
self.assertEqual(misc.stringToNone('None'), None)
|
||||||
|
|
||||||
def test_string_to_none_3(self):
|
def test_string_to_none_3(self):
|
||||||
self.assertEquals(misc.stringToNone(None), None)
|
self.assertEqual(misc.stringToNone(None), None)
|
||||||
|
|
||||||
def test_string_to_none_4(self):
|
def test_string_to_none_4(self):
|
||||||
self.assertEquals(misc.stringToNone('abcdef'), 'abcdef')
|
self.assertEqual(misc.stringToNone('abcdef'), 'abcdef')
|
||||||
|
|
||||||
def suite():
|
def suite():
|
||||||
suite = unittest.TestSuite()
|
suite = unittest.TestSuite()
|
||||||
|
|||||||
@@ -35,23 +35,23 @@ class TestWnettools(unittest.TestCase):
|
|||||||
|
|
||||||
def test_interface_name_sanitation(self):
|
def test_interface_name_sanitation(self):
|
||||||
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat')
|
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat')
|
||||||
self.assertEquals(interface.iface, 'blahblahuptimetmpblahcat')
|
self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat')
|
||||||
|
|
||||||
def test_freq_translation_low(self):
|
def test_freq_translation_low(self):
|
||||||
freq = '2.412 GHz'
|
freq = '2.412 GHz'
|
||||||
interface = wnettools.BaseWirelessInterface('wlan0')
|
interface = wnettools.BaseWirelessInterface('wlan0')
|
||||||
self.assertEquals(interface._FreqToChannel(freq), 1)
|
self.assertEqual(interface._FreqToChannel(freq), 1)
|
||||||
|
|
||||||
def test_freq_translation_high(self):
|
def test_freq_translation_high(self):
|
||||||
freq = '2.484 GHz'
|
freq = '2.484 GHz'
|
||||||
interface = wnettools.BaseWirelessInterface('wlan0')
|
interface = wnettools.BaseWirelessInterface('wlan0')
|
||||||
self.assertEquals(interface._FreqToChannel(freq), 14)
|
self.assertEqual(interface._FreqToChannel(freq), 14)
|
||||||
|
|
||||||
def test_generate_psk(self):
|
def test_generate_psk(self):
|
||||||
interface = wnettools.BaseWirelessInterface('wlan0')
|
interface = wnettools.BaseWirelessInterface('wlan0')
|
||||||
if 'wlan0' in wnettools.GetWirelessInterfaces():
|
if 'wlan0' in wnettools.GetWirelessInterfaces():
|
||||||
psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'})
|
psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'})
|
||||||
self.assertEquals(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be')
|
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be')
|
||||||
|
|
||||||
def suite():
|
def suite():
|
||||||
suite = unittest.TestSuite()
|
suite = unittest.TestSuite()
|
||||||
|
|||||||
@@ -35,9 +35,9 @@ try:
|
|||||||
dbusmanager.connect_to_dbus()
|
dbusmanager.connect_to_dbus()
|
||||||
daemon = dbusmanager.get_interface('daemon')
|
daemon = dbusmanager.get_interface('daemon')
|
||||||
wireless = dbusmanager.get_interface('wireless')
|
wireless = dbusmanager.get_interface('wireless')
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
print >> sys.stderr, "Exception caught: %s" % str(e)
|
print("Exception caught: %s" % str(e), file=sys.stderr)
|
||||||
print >> sys.stderr, 'Could not connect to daemon.'
|
print('Could not connect to daemon.', file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def handler(*args):
|
def handler(*args):
|
||||||
@@ -45,7 +45,7 @@ def handler(*args):
|
|||||||
pass
|
pass
|
||||||
def error_handler(*args):
|
def error_handler(*args):
|
||||||
""" Error handler. """
|
""" Error handler. """
|
||||||
print >> sys.stderr, 'Async error autoconnecting.'
|
print('Async error autoconnecting.', file=sys.stderr)
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
@@ -55,7 +55,7 @@ if __name__ == '__main__':
|
|||||||
if not daemon.CheckIfConnecting():
|
if not daemon.CheckIfConnecting():
|
||||||
daemon.AutoConnect(True, reply_handler=handler,
|
daemon.AutoConnect(True, reply_handler=handler,
|
||||||
error_handler=error_handler)
|
error_handler=error_handler)
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
print >> sys.stderr, "Exception caught: %s" % str(e)
|
print("Exception caught: %s" % str(e), file=sys.stderr)
|
||||||
print >> sys.stderr, 'Error autoconnecting.'
|
print('Error autoconnecting.', file=sys.stderr)
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ import wicd.wpath as wpath
|
|||||||
|
|
||||||
def fail(backend_name, reason):
|
def fail(backend_name, reason):
|
||||||
""" Helper to warn the user about failure in loading backend. """
|
""" 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
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ class BackendManager(object):
|
|||||||
|
|
||||||
def _load_backend(self, backend_name):
|
def _load_backend(self, backend_name):
|
||||||
""" Imports a backend and returns the loaded module. """
|
""" 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,
|
backend_path = os.path.join(self.backend_dir,
|
||||||
'be-' + backend_name + '.py')
|
'be-' + backend_name + '.py')
|
||||||
if self._valid_backend_file(backend_path):
|
if self._valid_backend_file(backend_path):
|
||||||
@@ -124,5 +124,5 @@ class BackendManager(object):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
self.__loaded_backend = backend
|
self.__loaded_backend = backend
|
||||||
print 'successfully loaded backend %s' % backend_name
|
print('successfully loaded backend %s' % backend_name)
|
||||||
return backend
|
return backend
|
||||||
|
|||||||
@@ -41,13 +41,13 @@ try:
|
|||||||
import iwscan
|
import iwscan
|
||||||
IWSCAN_AVAIL = True
|
IWSCAN_AVAIL = True
|
||||||
except ImportError:
|
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
|
IWSCAN_AVAIL = False
|
||||||
try:
|
try:
|
||||||
import wpactrl
|
import wpactrl
|
||||||
WPACTRL_AVAIL = True
|
WPACTRL_AVAIL = True
|
||||||
except ImportError:
|
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
|
WPACTRL_AVAIL = False
|
||||||
|
|
||||||
import re
|
import re
|
||||||
@@ -165,9 +165,9 @@ class Interface(BaseInterface):
|
|||||||
data = (self.iface + '\0' * 16)[:18]
|
data = (self.iface + '\0' * 16)[:18]
|
||||||
try:
|
try:
|
||||||
result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data)
|
result = fcntl.ioctl(self.sock.fileno(), SIOCGIFFLAGS, data)
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print "SIOCGIFFLAGS failed: " + str(e)
|
print("SIOCGIFFLAGS failed: " + str(e))
|
||||||
return False
|
return False
|
||||||
|
|
||||||
flags, = struct.unpack('H', result[16:18])
|
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]:
|
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
|
||||||
return self._mii_get_plugged_in()
|
return self._mii_get_plugged_in()
|
||||||
else:
|
else:
|
||||||
print ('Error: No way of checking for a wired connection. Make' +
|
print(('Error: No way of checking for a wired connection. Make' +
|
||||||
'sure that either mii-tool or ethtool is installed.')
|
'sure that either mii-tool or ethtool is installed.'))
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _eth_get_plugged_in(self):
|
def _eth_get_plugged_in(self):
|
||||||
@@ -224,9 +224,9 @@ class WiredInterface(Interface, BaseWiredInterface):
|
|||||||
data = (self.iface + '\0' * 16)[:16] + arg
|
data = (self.iface + '\0' * 16)[:16] + arg
|
||||||
try:
|
try:
|
||||||
fcntl.ioctl(self.sock.fileno(), SIOCETHTOOL, data)
|
fcntl.ioctl(self.sock.fileno(), SIOCETHTOOL, data)
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print 'SIOCETHTOOL failed: ' + str(e)
|
print('SIOCETHTOOL failed: ' + str(e))
|
||||||
return False
|
return False
|
||||||
return bool(buff.tolist()[1])
|
return bool(buff.tolist()[1])
|
||||||
|
|
||||||
@@ -244,9 +244,9 @@ class WiredInterface(Interface, BaseWiredInterface):
|
|||||||
0x0004, 0)
|
0x0004, 0)
|
||||||
try:
|
try:
|
||||||
result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff)
|
result = fcntl.ioctl(self.sock.fileno(), SIOCGMIIPHY, buff)
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print 'SIOCGMIIPHY failed: ' + str(e)
|
print('SIOCGMIIPHY failed: ' + str(e))
|
||||||
return False
|
return False
|
||||||
reg = struct.unpack('16shhhh', result)[-1]
|
reg = struct.unpack('16shhhh', result)[-1]
|
||||||
return bool(reg & 0x0004)
|
return bool(reg & 0x0004)
|
||||||
@@ -286,16 +286,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
if not self.scan_iface:
|
if not self.scan_iface:
|
||||||
try:
|
try:
|
||||||
self.scan_iface = iwscan.WirelessInterface(self.iface)
|
self.scan_iface = iwscan.WirelessInterface(self.iface)
|
||||||
except iwscan.error, e:
|
except iwscan.error as e:
|
||||||
print "GetNetworks caught an exception: %s" % e
|
print("GetNetworks caught an exception: %s" % e)
|
||||||
return []
|
return []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
results = self.scan_iface.Scan()
|
results = self.scan_iface.Scan()
|
||||||
except iwscan.error, e:
|
except iwscan.error as e:
|
||||||
print "ERROR: %s" % e
|
print("ERROR: %s" % e)
|
||||||
return []
|
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):
|
def _parse_ap(self, cell):
|
||||||
""" Parse a single cell from the python-iwscan list. """
|
""" Parse a single cell from the python-iwscan list. """
|
||||||
@@ -303,7 +303,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
try:
|
try:
|
||||||
ap['essid'] = misc.to_unicode(cell['essid'])
|
ap['essid'] = misc.to_unicode(cell['essid'])
|
||||||
except UnicodeError:
|
except UnicodeError:
|
||||||
print 'Unicode problem with the current network essid, ignoring!!'
|
print('Unicode problem with the current network essid, ignoring!!')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if ap['essid'] in [ "", '<hidden>']:
|
if ap['essid'] in [ "", '<hidden>']:
|
||||||
@@ -356,12 +356,12 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
if os.path.exists(socket_loc):
|
if os.path.exists(socket_loc):
|
||||||
try:
|
try:
|
||||||
return wpactrl.WPACtrl(socket_loc)
|
return wpactrl.WPACtrl(socket_loc)
|
||||||
except wpactrl.error, e:
|
except wpactrl.error as e:
|
||||||
print "Couldn't open ctrl_interface: %s" % e
|
print("Couldn't open ctrl_interface: %s" % e)
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
|
print("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
|
||||||
% self.iface
|
% self.iface)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def ValidateAuthentication(self, auth_time):
|
def ValidateAuthentication(self, auth_time):
|
||||||
@@ -392,7 +392,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
|
|
||||||
wpa = self._connect_to_wpa_ctrl_iface()
|
wpa = self._connect_to_wpa_ctrl_iface()
|
||||||
if not wpa:
|
if not wpa:
|
||||||
print "Failed to open ctrl interface"
|
print("Failed to open ctrl interface")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
MAX_TIME = 35
|
MAX_TIME = 35
|
||||||
@@ -402,12 +402,12 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
try:
|
try:
|
||||||
status = wpa.request("STATUS").split("\n")
|
status = wpa.request("STATUS").split("\n")
|
||||||
except:
|
except:
|
||||||
print "wpa_supplicant status query failed."
|
print("wpa_supplicant status query failed.")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print 'wpa_supplicant ctrl_interface status query is %s' \
|
print('wpa_supplicant ctrl_interface status query is %s' \
|
||||||
% str(status)
|
% str(status))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
[result] = [l for l in status if l.startswith("wpa_state=")]
|
[result] = [l for l in status if l.startswith("wpa_state=")]
|
||||||
@@ -426,7 +426,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
disconnected_time = 0
|
disconnected_time = 0
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
print 'wpa_supplicant authentication may have failed.'
|
print('wpa_supplicant authentication may have failed.')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -458,28 +458,28 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
if info[2] == network.get('essid'):
|
if info[2] == network.get('essid'):
|
||||||
if info[5] == 'WEP' or (info[5] == 'OPEN' and \
|
if info[5] == 'WEP' or (info[5] == 'OPEN' and \
|
||||||
info[4] == 'WEP'):
|
info[4] == 'WEP'):
|
||||||
print 'Setting up WEP'
|
print('Setting up WEP')
|
||||||
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
||||||
network.get('key')])
|
network.get('key')])
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
else:
|
else:
|
||||||
if info[5] == 'SHARED' and info[4] == 'WEP':
|
if info[5] == 'SHARED' and info[4] == 'WEP':
|
||||||
print 'Setting up WEP'
|
print('Setting up WEP')
|
||||||
auth_mode = 'SHARED'
|
auth_mode = 'SHARED'
|
||||||
key_name = 'Key1'
|
key_name = 'Key1'
|
||||||
elif info[5] == 'WPA-PSK':
|
elif info[5] == 'WPA-PSK':
|
||||||
print 'Setting up WPA-PSK'
|
print('Setting up WPA-PSK')
|
||||||
auth_mode = 'WPAPSK'
|
auth_mode = 'WPAPSK'
|
||||||
key_name = 'WPAPSK'
|
key_name = 'WPAPSK'
|
||||||
elif info[5] == 'WPA2-PSK':
|
elif info[5] == 'WPA2-PSK':
|
||||||
print 'Setting up WPA2-PSK'
|
print('Setting up WPA2-PSK')
|
||||||
auth_mode = 'WPA2PSK'
|
auth_mode = 'WPA2PSK'
|
||||||
key_name = 'WPAPSK'
|
key_name = 'WPAPSK'
|
||||||
else:
|
else:
|
||||||
print 'Unknown AuthMode, can\'t complete ' + \
|
print('Unknown AuthMode, can\'t complete ' + \
|
||||||
'connection process!'
|
'connection process!')
|
||||||
return
|
return
|
||||||
|
|
||||||
cmd_list = []
|
cmd_list = []
|
||||||
@@ -495,7 +495,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
for cmd in cmd_list:
|
for cmd in cmd_list:
|
||||||
cmd = 'iwpriv ' + self.iface + ' '
|
cmd = 'iwpriv ' + self.iface + ' '
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface("")
|
@neediface("")
|
||||||
@@ -504,9 +504,9 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
data = (self.iface + '\0' * 32)[:32]
|
data = (self.iface + '\0' * 32)[:32]
|
||||||
try:
|
try:
|
||||||
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
|
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print "SIOCGIWAP failed: " + str(e)
|
print("SIOCGIWAP failed: " + str(e))
|
||||||
return ""
|
return ""
|
||||||
raw_addr = struct.unpack("xxBBBBBB", result[:8])
|
raw_addr = struct.unpack("xxBBBBBB", result[:8])
|
||||||
return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr
|
return "%02X:%02X:%02X:%02X:%02X:%02X" % raw_addr
|
||||||
@@ -519,9 +519,9 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
size = struct.calcsize(fmt)
|
size = struct.calcsize(fmt)
|
||||||
try:
|
try:
|
||||||
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRATE, data)[16:]
|
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRATE, data)[16:]
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print "SIOCGIWRATE failed: " + str(e)
|
print("SIOCGIWRATE failed: " + str(e))
|
||||||
return ""
|
return ""
|
||||||
f, e, x, x = struct.unpack(fmt, result[:size])
|
f, e, x, x = struct.unpack(fmt, result[:size])
|
||||||
return "%s %s" % ((f / 1000000), 'Mb/s')
|
return "%s %s" % ((f / 1000000), 'Mb/s')
|
||||||
@@ -562,9 +562,9 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
iwfreq = (self.iface + '\0' * 16)[:16] + arg
|
iwfreq = (self.iface + '\0' * 16)[:16] + arg
|
||||||
try:
|
try:
|
||||||
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRANGE, iwfreq)
|
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWRANGE, iwfreq)
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print "SIOCGIWRANGE failed: " + str(e)
|
print("SIOCGIWRANGE failed: " + str(e))
|
||||||
return None
|
return None
|
||||||
# This defines the iwfreq struct, used to get signal strength.
|
# This defines the iwfreq struct, used to get signal strength.
|
||||||
fmt = "iiihb6ii4B4Bi32i2i2i2i2i3h8h2b2bhi8i2b3h2i2ihB17x" + 32 * "ihbb"
|
fmt = "iiihb6ii4B4Bi32i2i2i2i2i3h8h2b2bhi8i2b3h2i2ihB17x" + 32 * "ihbb"
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ reusable for other purposes as well.
|
|||||||
|
|
||||||
import sys, os
|
import sys, os
|
||||||
|
|
||||||
from ConfigParser import RawConfigParser, ParsingError
|
from configparser import RawConfigParser, ParsingError
|
||||||
import codecs
|
import codecs
|
||||||
|
|
||||||
from wicd.misc import Noneify, to_unicode
|
from wicd.misc import Noneify, to_unicode
|
||||||
@@ -61,8 +61,8 @@ class ConfigManager(RawConfigParser):
|
|||||||
self.write()
|
self.write()
|
||||||
try:
|
try:
|
||||||
self.read(path)
|
self.read(path)
|
||||||
except ParsingError, p:
|
except ParsingError as p:
|
||||||
print "Could not start wicd: %s" % p.message
|
print("Could not start wicd: %s" % p.message)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
@@ -86,7 +86,7 @@ class ConfigManager(RawConfigParser):
|
|||||||
"""
|
"""
|
||||||
if not self.has_section(section):
|
if not self.has_section(section):
|
||||||
self.add_section(section)
|
self.add_section(section)
|
||||||
if isinstance(value, basestring):
|
if isinstance(value, str):
|
||||||
value = to_unicode(value)
|
value = to_unicode(value)
|
||||||
if value.startswith(' ') or value.endswith(' '):
|
if value.startswith(' ') or value.endswith(' '):
|
||||||
value = "%(ws)s%(value)s%(ws)s" % {"value" : value,
|
value = "%(ws)s%(value)s%(ws)s" % {"value" : value,
|
||||||
@@ -115,7 +115,7 @@ class ConfigManager(RawConfigParser):
|
|||||||
|
|
||||||
if self.has_option(section, option):
|
if self.has_option(section, option):
|
||||||
ret = RawConfigParser.get(self, 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)):
|
and ret.endswith(self.mrk_ws)):
|
||||||
ret = ret[3:-3]
|
ret = ret[3:-3]
|
||||||
ret = to_unicode(ret)
|
ret = to_unicode(ret)
|
||||||
@@ -125,15 +125,15 @@ class ConfigManager(RawConfigParser):
|
|||||||
if option in ['apsk', 'password', 'identity', \
|
if option in ['apsk', 'password', 'identity', \
|
||||||
'private_key', 'private_key_passwd', \
|
'private_key', 'private_key_passwd', \
|
||||||
'key', 'passphrase']:
|
'key', 'passphrase']:
|
||||||
print ''.join(['found ', option, \
|
print(''.join(['found ', option, \
|
||||||
' in configuration *****'])
|
' in configuration *****']))
|
||||||
else:
|
else:
|
||||||
print ''.join(['found ', option, ' in configuration ',
|
print(''.join(['found ', option, ' in configuration ',
|
||||||
str(ret)])
|
str(ret)]))
|
||||||
else: # Use the default, unless no default was provided
|
else: # Use the default, unless no default was provided
|
||||||
if default != "__None__":
|
if default != "__None__":
|
||||||
print 'did not find %s in configuration, setting default %s' \
|
print('did not find %s in configuration, setting default %s' \
|
||||||
% (option, str(default))
|
% (option, str(default)))
|
||||||
self.set(section, option, str(default), write=True)
|
self.set(section, option, str(default), write=True)
|
||||||
ret = default
|
ret = default
|
||||||
else:
|
else:
|
||||||
@@ -146,7 +146,7 @@ class ConfigManager(RawConfigParser):
|
|||||||
except (ValueError, TypeError, AttributeError):
|
except (ValueError, TypeError, AttributeError):
|
||||||
ret = Noneify(ret)
|
ret = Noneify(ret)
|
||||||
# This is a workaround for a python-dbus issue on 64-bit systems.
|
# This is a workaround for a python-dbus issue on 64-bit systems.
|
||||||
if isinstance(ret, (int, long)):
|
if isinstance(ret, int):
|
||||||
try:
|
try:
|
||||||
Int32(ret)
|
Int32(ret)
|
||||||
except OverflowError:
|
except OverflowError:
|
||||||
|
|||||||
46
wicd/misc.py
46
wicd/misc.py
@@ -30,8 +30,8 @@ import string
|
|||||||
import gobject
|
import gobject
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
from subprocess import Popen, STDOUT, PIPE, call
|
from subprocess import Popen, STDOUT, PIPE, call
|
||||||
from commands import getoutput
|
from subprocess import getoutput
|
||||||
from itertools import repeat, chain, izip
|
from itertools import repeat, chain
|
||||||
from pipes import quote
|
from pipes import quote
|
||||||
import socket
|
import socket
|
||||||
|
|
||||||
@@ -154,8 +154,8 @@ def Run(cmd, include_stderr=False, return_pipe=False,
|
|||||||
try:
|
try:
|
||||||
f = Popen(cmd, shell=False, stdout=PIPE, stdin=std_in, stderr=err,
|
f = Popen(cmd, shell=False, stdout=PIPE, stdin=std_in, stderr=err,
|
||||||
close_fds=fds, cwd='/', env=tmpenv)
|
close_fds=fds, cwd='/', env=tmpenv)
|
||||||
except OSError, e:
|
except OSError as e:
|
||||||
print "Running command %s failed: %s" % (str(cmd), str(e))
|
print("Running command %s failed: %s" % (str(cmd), str(e)))
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
if return_obj:
|
if return_obj:
|
||||||
@@ -252,10 +252,10 @@ def ExecuteScript(script, verbose=False, extra_parameters=()):
|
|||||||
# escape script name
|
# escape script name
|
||||||
script = quote(script)
|
script = quote(script)
|
||||||
if verbose:
|
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)
|
ret = call('%s %s > /dev/null 2>&1' % (script, params), shell=True)
|
||||||
if verbose:
|
if verbose:
|
||||||
print "%s returned %s" % (script, ret)
|
print("%s returned %s" % (script, ret))
|
||||||
|
|
||||||
def ReadFile(filename):
|
def ReadFile(filename):
|
||||||
""" read in a file and return it's contents as a string """
|
""" read in a file and return it's contents as a string """
|
||||||
@@ -322,9 +322,9 @@ def ParseEncryption(network):
|
|||||||
if rep_val:
|
if rep_val:
|
||||||
line = line.replace("$_%s" % cur_val, str(rep_val))
|
line = line.replace("$_%s" % cur_val, str(rep_val))
|
||||||
else:
|
else:
|
||||||
print "Ignoring template line: '%s'" % line
|
print("Ignoring template line: '%s'" % line)
|
||||||
else:
|
else:
|
||||||
print "Weird parsing error occurred"
|
print("Weird parsing error occurred")
|
||||||
config_file = ''.join([config_file, line])
|
config_file = ''.join([config_file, line])
|
||||||
else: # Just a regular entry.
|
else: # Just a regular entry.
|
||||||
config_file = ''.join([config_file, line])
|
config_file = ''.join([config_file, line])
|
||||||
@@ -337,7 +337,7 @@ def ParseEncryption(network):
|
|||||||
file_name = 'wired'
|
file_name = 'wired'
|
||||||
file_loc = os.path.join(wpath.networks, file_name)
|
file_loc = os.path.join(wpath.networks, file_name)
|
||||||
f = open(file_loc, "w")
|
f = open(file_loc, "w")
|
||||||
os.chmod(file_loc, 0600)
|
os.chmod(file_loc, 0o600)
|
||||||
os.chown(file_loc, 0, 0)
|
os.chown(file_loc, 0, 0)
|
||||||
# We could do this above, but we'd like to read protect
|
# We could do this above, but we'd like to read protect
|
||||||
# them before we write, so that it can't be read.
|
# them before we write, so that it can't be read.
|
||||||
@@ -358,8 +358,8 @@ def LoadEncryptionMethods(wired = False):
|
|||||||
active_fname = "active"
|
active_fname = "active"
|
||||||
try:
|
try:
|
||||||
enctypes = open(wpath.encryption + active_fname,"r").readlines()
|
enctypes = open(wpath.encryption + active_fname,"r").readlines()
|
||||||
except IOError, e:
|
except IOError as e:
|
||||||
print "Fatal Error: template index file is missing."
|
print("Fatal Error: template index file is missing.")
|
||||||
raise IOError(e)
|
raise IOError(e)
|
||||||
|
|
||||||
# Parse each encryption method
|
# Parse each encryption method
|
||||||
@@ -391,7 +391,7 @@ def _parse_enc_template(enctype):
|
|||||||
try:
|
try:
|
||||||
f = open(os.path.join(wpath.encryption, enctype), "r")
|
f = open(os.path.join(wpath.encryption, enctype), "r")
|
||||||
except IOError:
|
except IOError:
|
||||||
print "Failed to open template file %s" % enctype
|
print("Failed to open template file %s" % enctype)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
cur_type = {}
|
cur_type = {}
|
||||||
@@ -408,7 +408,7 @@ def _parse_enc_template(enctype):
|
|||||||
cur_type["required"] = __parse_field_ent(parse_ent(line, "require"))
|
cur_type["required"] = __parse_field_ent(parse_ent(line, "require"))
|
||||||
if not cur_type["required"]:
|
if not cur_type["required"]:
|
||||||
# An error occured parsing the require line.
|
# 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
|
continue
|
||||||
elif line.startswith("optional"):
|
elif line.startswith("optional"):
|
||||||
cur_type["optional"] = __parse_field_ent(parse_ent(line,
|
cur_type["optional"] = __parse_field_ent(parse_ent(line,
|
||||||
@@ -416,7 +416,7 @@ def _parse_enc_template(enctype):
|
|||||||
field_type="optional")
|
field_type="optional")
|
||||||
if not cur_type["optional"]:
|
if not cur_type["optional"]:
|
||||||
# An error occured parsing the optional line.
|
# 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
|
continue
|
||||||
elif line.startswith("protected"):
|
elif line.startswith("protected"):
|
||||||
cur_type["protected"] = __parse_field_ent(
|
cur_type["protected"] = __parse_field_ent(
|
||||||
@@ -425,17 +425,17 @@ def _parse_enc_template(enctype):
|
|||||||
)
|
)
|
||||||
if not cur_type["protected"]:
|
if not cur_type["protected"]:
|
||||||
# An error occured parsing the protected line.
|
# 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
|
continue
|
||||||
elif line.startswith("----"):
|
elif line.startswith("----"):
|
||||||
# We're done.
|
# We're done.
|
||||||
break
|
break
|
||||||
f.close()
|
f.close()
|
||||||
if not cur_type["required"]:
|
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
|
return None
|
||||||
if not cur_type["name"]:
|
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
|
return None
|
||||||
else:
|
else:
|
||||||
return cur_type
|
return cur_type
|
||||||
@@ -476,9 +476,9 @@ def sanitize_escaped(s):
|
|||||||
def to_unicode(x):
|
def to_unicode(x):
|
||||||
""" Attempts to convert a string to utf-8. """
|
""" Attempts to convert a string to utf-8. """
|
||||||
# If this is a unicode string, encode it and return
|
# If this is a unicode string, encode it and return
|
||||||
if not isinstance(x, basestring):
|
if not isinstance(x, str):
|
||||||
return x
|
return x
|
||||||
if isinstance(x, unicode):
|
if isinstance(x, str):
|
||||||
return x.encode('utf-8')
|
return x.encode('utf-8')
|
||||||
|
|
||||||
x = sanitize_escaped(x)
|
x = sanitize_escaped(x)
|
||||||
@@ -500,7 +500,7 @@ def to_unicode(x):
|
|||||||
def RenameProcess(new_name):
|
def RenameProcess(new_name):
|
||||||
""" Renames the process calling the function to the given name. """
|
""" Renames the process calling the function to the given name. """
|
||||||
if 'linux' not in sys.platform:
|
if 'linux' not in sys.platform:
|
||||||
print 'Unsupported platform'
|
print('Unsupported platform')
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
import ctypes
|
import ctypes
|
||||||
@@ -509,7 +509,7 @@ def RenameProcess(new_name):
|
|||||||
libc.prctl(15, new_name, 0, 0, 0)
|
libc.prctl(15, new_name, 0, 0, 0)
|
||||||
return True
|
return True
|
||||||
except:
|
except:
|
||||||
print "rename failed"
|
print("rename failed")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def detect_desktop_environment():
|
def detect_desktop_environment():
|
||||||
@@ -639,7 +639,7 @@ def izip_longest(*args, **kwds):
|
|||||||
fillers = repeat(fillvalue)
|
fillers = repeat(fillvalue)
|
||||||
iters = [chain(it, sentinel(), fillers) for it in args]
|
iters = [chain(it, sentinel(), fillers) for it in args]
|
||||||
try:
|
try:
|
||||||
for tup in izip(*iters):
|
for tup in zip(*iters):
|
||||||
yield tup
|
yield tup
|
||||||
except IndexError:
|
except IndexError:
|
||||||
pass
|
pass
|
||||||
@@ -651,4 +651,4 @@ def grouper(n, iterable, fillvalue=None):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
args = [iter(iterable)] * n
|
args = [iter(iterable)] * n
|
||||||
return izip_longest(fillvalue=fillvalue, *args)
|
return zip_longest(fillvalue=fillvalue, *args)
|
||||||
|
|||||||
@@ -55,8 +55,8 @@ def diewithdbus(func):
|
|||||||
ret = func(self, *__args, **__kargs)
|
ret = func(self, *__args, **__kargs)
|
||||||
self.__lost_dbus_count = 0
|
self.__lost_dbus_count = 0
|
||||||
return ret
|
return ret
|
||||||
except DBusException, e:
|
except DBusException as e:
|
||||||
print "Caught exception %s" % str(e)
|
print("Caught exception %s" % str(e))
|
||||||
if not hasattr(self, "__lost_dbus_count"):
|
if not hasattr(self, "__lost_dbus_count"):
|
||||||
self.__lost_dbus_count = 0
|
self.__lost_dbus_count = 0
|
||||||
if self.__lost_dbus_count > 3:
|
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),
|
# If we haven't gotten any signal 4 runs in a row (12 seconds),
|
||||||
# try to reconnect.
|
# try to reconnect.
|
||||||
self.connection_lost_counter += 1
|
self.connection_lost_counter += 1
|
||||||
print self.connection_lost_counter
|
print(self.connection_lost_counter)
|
||||||
if self.connection_lost_counter >= 4 and daemon.GetAutoReconnect():
|
if self.connection_lost_counter >= 4 and daemon.GetAutoReconnect():
|
||||||
wireless.DisconnectWireless()
|
wireless.DisconnectWireless()
|
||||||
self.connection_lost_counter = 0
|
self.connection_lost_counter = 0
|
||||||
@@ -218,7 +218,7 @@ class ConnectionStatus(object):
|
|||||||
wifi_ip = None
|
wifi_ip = None
|
||||||
|
|
||||||
if daemon.GetSuspend():
|
if daemon.GetSuspend():
|
||||||
print "Suspended."
|
print("Suspended.")
|
||||||
state = misc.SUSPENDED
|
state = misc.SUSPENDED
|
||||||
return self.update_state(state)
|
return self.update_state(state)
|
||||||
|
|
||||||
@@ -251,7 +251,7 @@ class ConnectionStatus(object):
|
|||||||
# Don't trigger it if the gui is open, because autoconnect
|
# Don't trigger it if the gui is open, because autoconnect
|
||||||
# is disabled while it's open.
|
# is disabled while it's open.
|
||||||
if not daemon.GetGUIOpen():
|
if not daemon.GetGUIOpen():
|
||||||
print 'Killing wireless connection to switch to wired...'
|
print('Killing wireless connection to switch to wired...')
|
||||||
wireless.DisconnectWireless()
|
wireless.DisconnectWireless()
|
||||||
daemon.AutoConnect(False, reply_handler=lambda *a:None,
|
daemon.AutoConnect(False, reply_handler=lambda *a:None,
|
||||||
error_handler=lambda *a:None)
|
error_handler=lambda *a:None)
|
||||||
@@ -291,7 +291,7 @@ class ConnectionStatus(object):
|
|||||||
self.reconnect_tries = 0
|
self.reconnect_tries = 0
|
||||||
info = [str(wired_ip)]
|
info = [str(wired_ip)]
|
||||||
else:
|
else:
|
||||||
print 'ERROR: Invalid state!'
|
print('ERROR: Invalid state!')
|
||||||
return True
|
return True
|
||||||
|
|
||||||
daemon.SetConnectionStatus(state, info)
|
daemon.SetConnectionStatus(state, info)
|
||||||
@@ -345,14 +345,14 @@ class ConnectionStatus(object):
|
|||||||
# Some checks to keep reconnect retries from going crazy.
|
# Some checks to keep reconnect retries from going crazy.
|
||||||
if (self.reconnect_tries > 3 and
|
if (self.reconnect_tries > 3 and
|
||||||
(time.time() - self.last_reconnect_time) < 200):
|
(time.time() - self.last_reconnect_time) < 200):
|
||||||
print "Throttling autoreconnect"
|
print("Throttling autoreconnect")
|
||||||
return
|
return
|
||||||
|
|
||||||
self.reconnecting = True
|
self.reconnecting = True
|
||||||
daemon.SetCurrentInterface('')
|
daemon.SetCurrentInterface('')
|
||||||
|
|
||||||
if daemon.ShouldAutoReconnect():
|
if daemon.ShouldAutoReconnect():
|
||||||
print 'Starting automatic reconnect process'
|
print('Starting automatic reconnect process')
|
||||||
self.last_reconnect_time = time.time()
|
self.last_reconnect_time = time.time()
|
||||||
self.reconnect_tries += 1
|
self.reconnect_tries += 1
|
||||||
|
|
||||||
@@ -362,10 +362,10 @@ class ConnectionStatus(object):
|
|||||||
if from_wireless and cur_net_id > -1:
|
if from_wireless and cur_net_id > -1:
|
||||||
# make sure disconnect scripts are run
|
# make sure disconnect scripts are run
|
||||||
# before we reconnect
|
# before we reconnect
|
||||||
print 'Disconnecting from network'
|
print('Disconnecting from network')
|
||||||
wireless.DisconnectWireless()
|
wireless.DisconnectWireless()
|
||||||
print 'Trying to reconnect to last used wireless ' + \
|
print('Trying to reconnect to last used wireless ' + \
|
||||||
'network'
|
'network')
|
||||||
wireless.ConnectWireless(cur_net_id)
|
wireless.ConnectWireless(cur_net_id)
|
||||||
else:
|
else:
|
||||||
daemon.AutoConnect(True, reply_handler=reply_handle,
|
daemon.AutoConnect(True, reply_handler=reply_handle,
|
||||||
|
|||||||
@@ -50,10 +50,10 @@ import os
|
|||||||
from signal import SIGTERM
|
from signal import SIGTERM
|
||||||
|
|
||||||
# wicd imports
|
# wicd imports
|
||||||
import misc
|
from . import misc
|
||||||
import wpath
|
import wpath
|
||||||
from backend import BackendManager
|
from .backend import BackendManager
|
||||||
from translations import _
|
from .translations import _
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
wpath.chdir(__file__)
|
wpath.chdir(__file__)
|
||||||
@@ -123,9 +123,9 @@ def expand_script_macros(script, msg, bssid, essid):
|
|||||||
"""
|
"""
|
||||||
def repl(match):
|
def repl(match):
|
||||||
macro = match.group(1).lower()
|
macro = match.group(1).lower()
|
||||||
if macro_dict.has_key(macro):
|
if macro in macro_dict:
|
||||||
return macro_dict[macro]
|
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()
|
return match.group()
|
||||||
|
|
||||||
macro_dict = { 'script' : msg,
|
macro_dict = { 'script' : msg,
|
||||||
@@ -133,7 +133,7 @@ def expand_script_macros(script, msg, bssid, essid):
|
|||||||
'essid' : essid }
|
'essid' : essid }
|
||||||
regex = re.compile(r'%\{([a-zA-Z0-9]+)\}')
|
regex = re.compile(r'%\{([a-zA-Z0-9]+)\}')
|
||||||
expanded = regex.sub(repl, script)
|
expanded = regex.sub(repl, script)
|
||||||
print "Expanded '%s' to '%s'" % (script, expanded)
|
print("Expanded '%s' to '%s'" % (script, expanded))
|
||||||
return expanded
|
return expanded
|
||||||
|
|
||||||
|
|
||||||
@@ -223,7 +223,7 @@ class Controller(object):
|
|||||||
misc.ExecuteScripts(wpath.predisconnectscripts, self.debug,
|
misc.ExecuteScripts(wpath.predisconnectscripts, self.debug,
|
||||||
extra_parameters=(nettype, name, mac))
|
extra_parameters=(nettype, name, mac))
|
||||||
if self.pre_disconnect_script:
|
if self.pre_disconnect_script:
|
||||||
print 'Running pre-disconnect script'
|
print('Running pre-disconnect script')
|
||||||
misc.ExecuteScript(expand_script_macros(self.pre_disconnect_script,
|
misc.ExecuteScript(expand_script_macros(self.pre_disconnect_script,
|
||||||
'pre-disconnection',
|
'pre-disconnection',
|
||||||
mac, name),
|
mac, name),
|
||||||
@@ -237,7 +237,7 @@ class Controller(object):
|
|||||||
misc.ExecuteScripts(wpath.postdisconnectscripts, self.debug,
|
misc.ExecuteScripts(wpath.postdisconnectscripts, self.debug,
|
||||||
extra_parameters=(nettype, name, mac))
|
extra_parameters=(nettype, name, mac))
|
||||||
if self.post_disconnect_script:
|
if self.post_disconnect_script:
|
||||||
print 'Running post-disconnect script'
|
print('Running post-disconnect script')
|
||||||
misc.ExecuteScript(expand_script_macros(self.post_disconnect_script,
|
misc.ExecuteScript(expand_script_macros(self.post_disconnect_script,
|
||||||
'post-disconnection',
|
'post-disconnection',
|
||||||
mac, name),
|
mac, name),
|
||||||
@@ -249,7 +249,7 @@ class Controller(object):
|
|||||||
|
|
||||||
def KillDHCP(self):
|
def KillDHCP(self):
|
||||||
""" Kill the managed DHCP client if its in a connecting state. """
|
""" 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
|
if (self.connecting_thread.is_connecting and
|
||||||
self.iface.dhcp_object):
|
self.iface.dhcp_object):
|
||||||
if self.iface.dhcp_object.poll() is None:
|
if self.iface.dhcp_object.poll() is None:
|
||||||
@@ -403,14 +403,14 @@ class ConnectThread(threading.Thread):
|
|||||||
routing entry is created.
|
routing entry is created.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
print 'Setting false IP...'
|
print('Setting false IP...')
|
||||||
self.SetStatus('resetting_ip_address')
|
self.SetStatus('resetting_ip_address')
|
||||||
iface.SetAddress('0.0.0.0')
|
iface.SetAddress('0.0.0.0')
|
||||||
|
|
||||||
@abortable
|
@abortable
|
||||||
def put_iface_down(self, iface):
|
def put_iface_down(self, iface):
|
||||||
""" Puts the given interface down. """
|
""" Puts the given interface down. """
|
||||||
print 'Putting interface down'
|
print('Putting interface down')
|
||||||
self.SetStatus('interface_down')
|
self.SetStatus('interface_down')
|
||||||
iface.Down()
|
iface.Down()
|
||||||
|
|
||||||
@@ -430,7 +430,7 @@ class ConnectThread(threading.Thread):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
if script:
|
if script:
|
||||||
print 'Executing %s script' % (msg)
|
print('Executing %s script' % (msg))
|
||||||
misc.ExecuteScript(expand_script_macros(script, msg, bssid, essid),
|
misc.ExecuteScript(expand_script_macros(script, msg, bssid, essid),
|
||||||
self.debug)
|
self.debug)
|
||||||
|
|
||||||
@@ -438,7 +438,7 @@ class ConnectThread(threading.Thread):
|
|||||||
def flush_routes(self, iface):
|
def flush_routes(self, iface):
|
||||||
""" Flush the routes for both wired/wireless interfaces. """
|
""" Flush the routes for both wired/wireless interfaces. """
|
||||||
self.SetStatus('flushing_routing_table')
|
self.SetStatus('flushing_routing_table')
|
||||||
print 'Flushing the routing table...'
|
print('Flushing the routing table...')
|
||||||
iface.FlushRoutes()
|
iface.FlushRoutes()
|
||||||
|
|
||||||
@abortable
|
@abortable
|
||||||
@@ -446,7 +446,7 @@ class ConnectThread(threading.Thread):
|
|||||||
""" Set the broadcast address for the given interface. """
|
""" Set the broadcast address for the given interface. """
|
||||||
if not self.network.get('broadcast') == None:
|
if not self.network.get('broadcast') == None:
|
||||||
self.SetStatus('setting_broadcast_address')
|
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'])
|
iface.SetAddress(broadcast=self.network['broadcast'])
|
||||||
|
|
||||||
@abortable
|
@abortable
|
||||||
@@ -458,10 +458,10 @@ class ConnectThread(threading.Thread):
|
|||||||
"""
|
"""
|
||||||
if self.network.get('ip'):
|
if self.network.get('ip'):
|
||||||
self.SetStatus('setting_static_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'])
|
iface.SetAddress(self.network['ip'], self.network['netmask'])
|
||||||
if self.network.get('gateway'):
|
if self.network.get('gateway'):
|
||||||
print 'Setting default gateway : ' + self.network['gateway']
|
print('Setting default gateway : ' + self.network['gateway'])
|
||||||
iface.SetDefaultRoute(self.network['gateway'])
|
iface.SetDefaultRoute(self.network['gateway'])
|
||||||
else:
|
else:
|
||||||
# Run dhcp...
|
# Run dhcp...
|
||||||
@@ -472,10 +472,10 @@ class ConnectThread(threading.Thread):
|
|||||||
self.network['dhcphostname'] = os.uname()[1]
|
self.network['dhcphostname'] = os.uname()[1]
|
||||||
if self.network['usedhcphostname']:
|
if self.network['usedhcphostname']:
|
||||||
hname = self.network['dhcphostname']
|
hname = self.network['dhcphostname']
|
||||||
print "Running DHCP with hostname", hname
|
print("Running DHCP with hostname", hname)
|
||||||
else:
|
else:
|
||||||
hname = None
|
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
|
# Check if a global DNS is configured. If it is, then let the DHCP know *not* to update resolv.conf
|
||||||
staticdns = False
|
staticdns = False
|
||||||
@@ -525,7 +525,7 @@ class ConnectThread(threading.Thread):
|
|||||||
@abortable
|
@abortable
|
||||||
def release_dhcp_clients(self, iface):
|
def release_dhcp_clients(self, iface):
|
||||||
""" Release all running dhcp clients. """
|
""" Release all running dhcp clients. """
|
||||||
print "Releasing DHCP leases..."
|
print("Releasing DHCP leases...")
|
||||||
iface.ReleaseDHCP()
|
iface.ReleaseDHCP()
|
||||||
|
|
||||||
def connect_aborted(self, reason):
|
def connect_aborted(self, reason):
|
||||||
@@ -536,7 +536,7 @@ class ConnectThread(threading.Thread):
|
|||||||
self.is_aborted = True
|
self.is_aborted = True
|
||||||
self.connect_result = reason
|
self.connect_result = reason
|
||||||
self.is_connecting = False
|
self.is_connecting = False
|
||||||
print 'exiting connection thread'
|
print('exiting connection thread')
|
||||||
|
|
||||||
def abort_connection(self, reason=""):
|
def abort_connection(self, reason=""):
|
||||||
""" Schedule a connection abortion for the given reason. """
|
""" Schedule a connection abortion for the given reason. """
|
||||||
@@ -556,13 +556,13 @@ class ConnectThread(threading.Thread):
|
|||||||
@abortable
|
@abortable
|
||||||
def stop_wpa(self, iface):
|
def stop_wpa(self, iface):
|
||||||
""" Stops wpa_supplicant. """
|
""" Stops wpa_supplicant. """
|
||||||
print 'Stopping wpa_supplicant'
|
print('Stopping wpa_supplicant')
|
||||||
iface.StopWPA()
|
iface.StopWPA()
|
||||||
|
|
||||||
@abortable
|
@abortable
|
||||||
def put_iface_up(self, iface):
|
def put_iface_up(self, iface):
|
||||||
""" Bring up given interface. """
|
""" Bring up given interface. """
|
||||||
print 'Putting interface up...'
|
print('Putting interface up...')
|
||||||
self.SetStatus('interface_up')
|
self.SetStatus('interface_up')
|
||||||
iface.Up()
|
iface.Up()
|
||||||
for x in range(0, 5):
|
for x in range(0, 5):
|
||||||
@@ -572,7 +572,7 @@ class ConnectThread(threading.Thread):
|
|||||||
self.abort_if_needed()
|
self.abort_if_needed()
|
||||||
|
|
||||||
# If we get here, the interface never came up
|
# 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):
|
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"
|
# Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX"
|
||||||
essid = misc.Noneify(essid)
|
essid = misc.Noneify(essid)
|
||||||
if essid is not None:
|
if essid is not None:
|
||||||
print 'Setting hidden essid ' + essid
|
print('Setting hidden essid ' + essid)
|
||||||
wiface.SetEssid(essid)
|
wiface.SetEssid(essid)
|
||||||
# sleep for a bit; scanning to fast will result in nothing
|
# sleep for a bit; scanning to fast will result in nothing
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
@@ -792,23 +792,23 @@ class Wireless(Controller):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
wiface = self.wiface
|
wiface = self.wiface
|
||||||
print 'Creating ad-hoc network'
|
print('Creating ad-hoc network')
|
||||||
print 'Stopping dhcp client and wpa_supplicant'
|
print('Stopping dhcp client and wpa_supplicant')
|
||||||
wiface.ReleaseDHCP()
|
wiface.ReleaseDHCP()
|
||||||
wiface.StopWPA()
|
wiface.StopWPA()
|
||||||
print 'Putting wireless interface down'
|
print('Putting wireless interface down')
|
||||||
wiface.Down()
|
wiface.Down()
|
||||||
print 'Setting mode, channel, and essid'
|
print('Setting mode, channel, and essid')
|
||||||
wiface.SetMode('ad-hoc')
|
wiface.SetMode('ad-hoc')
|
||||||
wiface.SetChannel(channel)
|
wiface.SetChannel(channel)
|
||||||
wiface.SetEssid(essid)
|
wiface.SetEssid(essid)
|
||||||
# Right now it just assumes you're using WEP
|
# Right now it just assumes you're using WEP
|
||||||
if enc_used:
|
if enc_used:
|
||||||
print 'Setting encryption key'
|
print('Setting encryption key')
|
||||||
wiface.SetKey(key)
|
wiface.SetKey(key)
|
||||||
print 'Putting interface up'
|
print('Putting interface up')
|
||||||
wiface.Up()
|
wiface.Up()
|
||||||
print 'Setting IP address'
|
print('Setting IP address')
|
||||||
wiface.SetAddress(ip, '255.255.255.0')
|
wiface.SetAddress(ip, '255.255.255.0')
|
||||||
|
|
||||||
def DetectWirelessInterface(self):
|
def DetectWirelessInterface(self):
|
||||||
@@ -843,10 +843,10 @@ class Wireless(Controller):
|
|||||||
action = 'block'
|
action = 'block'
|
||||||
for t in types:
|
for t in types:
|
||||||
cmd = ['rfkill', action, t]
|
cmd = ['rfkill', action, t]
|
||||||
print "rfkill: %sing %s" % (action, t)
|
print("rfkill: %sing %s" % (action, t))
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
return True
|
return True
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
raise e
|
raise e
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -858,9 +858,8 @@ class Wireless(Controller):
|
|||||||
"""
|
"""
|
||||||
cmd = 'rfkill list'
|
cmd = 'rfkill list'
|
||||||
rfkill_out = misc.Run(cmd)
|
rfkill_out = misc.Run(cmd)
|
||||||
soft_blocks = filter(lambda x: x.startswith('Soft'),
|
soft_blocks = [x for x in rfkill_out.split('\t') if x.startswith('Soft')]
|
||||||
rfkill_out.split('\t'))
|
for line in [x.strip() for x in soft_blocks]:
|
||||||
for line in map(lambda x: x.strip(), soft_blocks):
|
|
||||||
if line.endswith('yes'):
|
if line.endswith('yes'):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
@@ -983,7 +982,7 @@ class WirelessConnectThread(ConnectThread):
|
|||||||
if self.network.get('enctype'):
|
if self.network.get('enctype'):
|
||||||
self.SetStatus('validating_authentication')
|
self.SetStatus('validating_authentication')
|
||||||
if not wiface.ValidateAuthentication(time.time()):
|
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':
|
if not self.connect_result or self.connect_result == 'failed':
|
||||||
self.abort_connection('bad_pass')
|
self.abort_connection('bad_pass')
|
||||||
|
|
||||||
@@ -1003,9 +1002,9 @@ class WirelessConnectThread(ConnectThread):
|
|||||||
self.network['bssid'], self.network['essid'])
|
self.network['bssid'], self.network['essid'])
|
||||||
|
|
||||||
self.SetStatus('done')
|
self.SetStatus('done')
|
||||||
print 'Connecting thread exiting.'
|
print('Connecting thread exiting.')
|
||||||
if self.debug:
|
if self.debug:
|
||||||
print "IP Address is: " + str(wiface.GetIP())
|
print("IP Address is: " + str(wiface.GetIP()))
|
||||||
self.connect_result = "success"
|
self.connect_result = "success"
|
||||||
self.is_connecting = False
|
self.is_connecting = False
|
||||||
|
|
||||||
@@ -1020,17 +1019,17 @@ class WirelessConnectThread(ConnectThread):
|
|||||||
"""
|
"""
|
||||||
if self.network.get('gateway') and self.should_verify_ap:
|
if self.network.get('gateway') and self.should_verify_ap:
|
||||||
self.SetStatus('verifying_association')
|
self.SetStatus('verifying_association')
|
||||||
print "Verifying AP association..."
|
print("Verifying AP association...")
|
||||||
for tries in range(1, 11):
|
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'])
|
retcode = self.iface.VerifyAPAssociation(self.network['gateway'])
|
||||||
if retcode == 0:
|
if retcode == 0:
|
||||||
print "Successfully associated."
|
print("Successfully associated.")
|
||||||
break
|
break
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
#TODO this should be in wnettools.py
|
#TODO this should be in wnettools.py
|
||||||
if retcode:
|
if retcode:
|
||||||
print "Connection Failed: Failed to ping the access point!"
|
print("Connection Failed: Failed to ping the access point!")
|
||||||
# Clean up before aborting.
|
# Clean up before aborting.
|
||||||
iface.SetAddress('0.0.0.0')
|
iface.SetAddress('0.0.0.0')
|
||||||
iface.FlushRoutes()
|
iface.FlushRoutes()
|
||||||
@@ -1039,7 +1038,7 @@ class WirelessConnectThread(ConnectThread):
|
|||||||
iface.StopWPA()
|
iface.StopWPA()
|
||||||
self.abort_connection('association_failed')
|
self.abort_connection('association_failed')
|
||||||
else:
|
else:
|
||||||
print 'not verifying'
|
print('not verifying')
|
||||||
|
|
||||||
@abortable
|
@abortable
|
||||||
def generate_psk_and_authenticate(self, wiface):
|
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
|
# Check to see if we need to generate a PSK (only for non-ralink
|
||||||
# cards).
|
# cards).
|
||||||
if self.debug:
|
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 \
|
if self.network.get('key') and \
|
||||||
'wpa' in str(self.network.get('enctype')):
|
'wpa' in str(self.network.get('enctype')):
|
||||||
self.SetStatus('generating_psk')
|
self.SetStatus('generating_psk')
|
||||||
print 'Generating psk...'
|
print('Generating psk...')
|
||||||
self.network['psk'] = wiface.GeneratePSK(self.network)
|
self.network['psk'] = wiface.GeneratePSK(self.network)
|
||||||
|
|
||||||
if not self.network.get('psk'):
|
if not self.network.get('psk'):
|
||||||
self.network['psk'] = self.network['key']
|
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 ' + \
|
'wireless key.\nPlease report this error to the wicd ' + \
|
||||||
'developers!'
|
'developers!')
|
||||||
# Generate the wpa_supplicant file...
|
# Generate the wpa_supplicant file...
|
||||||
if self.network.get('enctype'):
|
if self.network.get('enctype'):
|
||||||
self.SetStatus('generating_wpa_config')
|
self.SetStatus('generating_wpa_config')
|
||||||
print 'Attempting to authenticate...'
|
print('Attempting to authenticate...')
|
||||||
wiface.Authenticate(self.network)
|
wiface.Authenticate(self.network)
|
||||||
|
|
||||||
|
|
||||||
@@ -1248,9 +1247,9 @@ class WiredConnectThread(ConnectThread):
|
|||||||
'wired')
|
'wired')
|
||||||
|
|
||||||
self.SetStatus('done')
|
self.SetStatus('done')
|
||||||
print 'Connecting thread exiting.'
|
print('Connecting thread exiting.')
|
||||||
if self.debug:
|
if self.debug:
|
||||||
print "IP Address is: " + str(liface.GetIP())
|
print("IP Address is: " + str(liface.GetIP()))
|
||||||
|
|
||||||
self.connect_result = "success"
|
self.connect_result = "success"
|
||||||
self.is_connecting = False
|
self.is_connecting = False
|
||||||
|
|||||||
@@ -32,9 +32,9 @@ try:
|
|||||||
bus = dbus.SystemBus()
|
bus = dbus.SystemBus()
|
||||||
proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
|
proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
|
||||||
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
|
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
print >> sys.stderr, "Exception caught: %s" % str(e)
|
print("Exception caught: %s" % str(e), file=sys.stderr)
|
||||||
print >> sys.stderr, 'Could not connect to daemon.'
|
print('Could not connect to daemon.', file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ if __name__ == '__main__':
|
|||||||
daemon.Disconnect()
|
daemon.Disconnect()
|
||||||
daemon.SetForcedDisconnect(False)
|
daemon.SetForcedDisconnect(False)
|
||||||
daemon.SetSuspend(True)
|
daemon.SetSuspend(True)
|
||||||
except Exception, e:
|
except Exception as e:
|
||||||
print >> sys.stderr, "Exception caught: %s" % str(e)
|
print("Exception caught: %s" % str(e), file=sys.stderr)
|
||||||
print >> sys.stderr, 'Error setting suspend.'
|
print('Error setting suspend.', file=sys.stderr)
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|||||||
@@ -44,9 +44,9 @@ def get_gettext():
|
|||||||
lc, encoding = locale.getdefaultlocale(envvars=('LC_MESSAGES',
|
lc, encoding = locale.getdefaultlocale(envvars=('LC_MESSAGES',
|
||||||
'LC_ALL', 'LANG',
|
'LC_ALL', 'LANG',
|
||||||
'LANGUAGE'))
|
'LANGUAGE'))
|
||||||
except ValueError, e:
|
except ValueError as e:
|
||||||
print str(e)
|
print(str(e))
|
||||||
print "Default locale unavailable, falling back to en_US"
|
print("Default locale unavailable, falling back to en_US")
|
||||||
if (lc):
|
if (lc):
|
||||||
langs += [lc]
|
langs += [lc]
|
||||||
langs += ["en_US"]
|
langs += ["en_US"]
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
|
|
||||||
# Scan since we just got started
|
# Scan since we just got started
|
||||||
if not auto_connect:
|
if not auto_connect:
|
||||||
print "--no-autoconnect detected, not autoconnecting..."
|
print("--no-autoconnect detected, not autoconnecting...")
|
||||||
self.SetForcedDisconnect(True)
|
self.SetForcedDisconnect(True)
|
||||||
self.wireless_bus.Scan()
|
self.wireless_bus.Scan()
|
||||||
|
|
||||||
@@ -161,7 +161,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetWiredInterface(self, interface):
|
def SetWiredInterface(self, interface):
|
||||||
""" Sets the wired interface for the daemon to use. """
|
""" 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
|
# Set it to a blank string, otherwise a network card named "None" will be searched
|
||||||
self.wired.wired_interface = noneToBlankString(interface)
|
self.wired.wired_interface = noneToBlankString(interface)
|
||||||
self.config.set("Settings", "wired_interface", interface, write=True)
|
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')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetWirelessInterface(self, interface):
|
def SetWirelessInterface(self, interface):
|
||||||
""" Sets the wireless interface the daemon will use. """
|
""" 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
|
# Set it to a blank string, otherwise a network card named "None" will be searched
|
||||||
self.wifi.wireless_interface = noneToBlankString(interface)
|
self.wifi.wireless_interface = noneToBlankString(interface)
|
||||||
self.config.set("Settings", "wireless_interface", interface, write=True)
|
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')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetWPADriver(self, driver):
|
def SetWPADriver(self, driver):
|
||||||
""" Sets the wpa driver the wpa_supplicant will use. """
|
""" 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.wifi.wpa_driver = driver
|
||||||
self.config.set("Settings", "wpa_driver", driver, write=True)
|
self.config.set("Settings", "wpa_driver", driver, write=True)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetUseGlobalDNS(self, use):
|
def SetUseGlobalDNS(self, use):
|
||||||
""" Sets a boolean which determines if global DNS is enabled. """
|
""" 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)
|
use = misc.to_bool(use)
|
||||||
self.config.set("Settings", "use_global_dns", use, write=True)
|
self.config.set("Settings", "use_global_dns", use, write=True)
|
||||||
self.use_global_dns = use
|
self.use_global_dns = use
|
||||||
@@ -195,7 +195,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None,
|
def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None,
|
||||||
dns_dom =None, search_dom=None):
|
dns_dom =None, search_dom=None):
|
||||||
""" Sets the global dns addresses. """
|
""" Sets the global dns addresses. """
|
||||||
print "setting global dns"
|
print("setting global dns")
|
||||||
self.config.set("Settings", "global_dns_1", misc.noneToString(dns1))
|
self.config.set("Settings", "global_dns_1", misc.noneToString(dns1))
|
||||||
self.dns1 = dns1
|
self.dns1 = dns1
|
||||||
self.wifi.global_dns_1 = dns1
|
self.wifi.global_dns_1 = dns1
|
||||||
@@ -218,26 +218,26 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
self.search_dom = search_dom
|
self.search_dom = search_dom
|
||||||
self.wifi.global_search_dom = search_dom
|
self.wifi.global_search_dom = search_dom
|
||||||
self.wired.global_search_dom = search_dom
|
self.wired.global_search_dom = search_dom
|
||||||
print 'global dns servers are', dns1, dns2, dns3
|
print('global dns servers are', dns1, dns2, dns3)
|
||||||
print 'domain is %s' % dns_dom
|
print('domain is %s' % dns_dom)
|
||||||
print 'search domain is %s' % search_dom
|
print('search domain is %s' % search_dom)
|
||||||
self.config.write()
|
self.config.write()
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetBackend(self, backend):
|
def SetBackend(self, backend):
|
||||||
""" Sets a new backend. """
|
""" Sets a new backend. """
|
||||||
print "setting backend to %s" % backend
|
print("setting backend to %s" % backend)
|
||||||
backends = networking.BACKEND_MGR.get_available_backends()
|
backends = networking.BACKEND_MGR.get_available_backends()
|
||||||
if backend not in backends:
|
if backend not in backends:
|
||||||
print "backend %s not available, trying to fallback to another" \
|
print("backend %s not available, trying to fallback to another" \
|
||||||
% backend
|
% backend)
|
||||||
try:
|
try:
|
||||||
backend = backends[0]
|
backend = backends[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
print "ERROR: no backends available!"
|
print("ERROR: no backends available!")
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
print "Fell back to backend %s" % backend
|
print("Fell back to backend %s" % backend)
|
||||||
self.config.set("Settings", "backend", backend, write=True)
|
self.config.set("Settings", "backend", backend, write=True)
|
||||||
if backend != self.GetCurrentBackend():
|
if backend != self.GetCurrentBackend():
|
||||||
self.suspended = True
|
self.suspended = True
|
||||||
@@ -364,18 +364,18 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
fails it tries a wireless connection.
|
fails it tries a wireless connection.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
print "Autoconnecting..."
|
print("Autoconnecting...")
|
||||||
if self.CheckIfConnecting():
|
if self.CheckIfConnecting():
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print 'Already connecting, doing nothing.'
|
print('Already connecting, doing nothing.')
|
||||||
return
|
return
|
||||||
if self.wired_bus.CheckPluggedIn():
|
if self.wired_bus.CheckPluggedIn():
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print "Starting wired autoconnect..."
|
print("Starting wired autoconnect...")
|
||||||
self._wired_autoconnect(fresh)
|
self._wired_autoconnect(fresh)
|
||||||
else:
|
else:
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print "Starting wireless autoconnect..."
|
print("Starting wireless autoconnect...")
|
||||||
self.wireless_bus._wireless_autoconnect(fresh)
|
self.wireless_bus._wireless_autoconnect(fresh)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
@@ -392,7 +392,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
and wait for the user to initiate reconnection.
|
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),
|
self.config.set("Settings", "auto_reconnect", misc.to_bool(value),
|
||||||
write=True)
|
write=True)
|
||||||
self.auto_reconnect = misc.to_bool(value)
|
self.auto_reconnect = misc.to_bool(value)
|
||||||
@@ -416,7 +416,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def CancelConnect(self):
|
def CancelConnect(self):
|
||||||
""" Cancels the wireless connection attempt """
|
""" Cancels the wireless connection attempt """
|
||||||
print 'canceling connection attempt'
|
print('canceling connection attempt')
|
||||||
if self.wifi.connecting_thread:
|
if self.wifi.connecting_thread:
|
||||||
self.wifi.connecting_thread.should_die = True
|
self.wifi.connecting_thread.should_die = True
|
||||||
self.wifi.ReleaseDHCP()
|
self.wifi.ReleaseDHCP()
|
||||||
@@ -478,7 +478,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
if self.debug_mode and value:
|
if self.debug_mode and value:
|
||||||
print "Forced disconnect on"
|
print("Forced disconnect on")
|
||||||
self.forced_disconnect = bool(value)
|
self.forced_disconnect = bool(value)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@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.
|
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.dhcp_client = int(client)
|
||||||
self.wifi.dhcp_client = int(client)
|
self.wifi.dhcp_client = int(client)
|
||||||
self.wired.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
|
# attempt to smartly connect to a wired network
|
||||||
# by using various wireless networks detected
|
# by using various wireless networks detected
|
||||||
# and by using plugged in USB devices
|
# and by using plugged in USB devices
|
||||||
print self.LastScan
|
print(self.LastScan)
|
||||||
if self.GetWiredAutoConnectMethod() == 2 and \
|
if self.GetWiredAutoConnectMethod() == 2 and \
|
||||||
not self.GetNeedWiredProfileChooser():
|
not self.GetNeedWiredProfileChooser():
|
||||||
self.LaunchChooser()
|
self.LaunchChooser()
|
||||||
@@ -740,8 +740,8 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
elif self.GetWiredAutoConnectMethod() == 1:
|
elif self.GetWiredAutoConnectMethod() == 1:
|
||||||
network = wiredb.GetDefaultWiredNetwork()
|
network = wiredb.GetDefaultWiredNetwork()
|
||||||
if not network:
|
if not network:
|
||||||
print "Couldn't find a default wired connection," + \
|
print("Couldn't find a default wired connection," + \
|
||||||
" wired autoconnect failed."
|
" wired autoconnect failed.")
|
||||||
self.wireless_bus._wireless_autoconnect(fresh)
|
self.wireless_bus._wireless_autoconnect(fresh)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -749,14 +749,14 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
else:
|
else:
|
||||||
network = wiredb.GetLastUsedWiredNetwork()
|
network = wiredb.GetLastUsedWiredNetwork()
|
||||||
if not network:
|
if not network:
|
||||||
print "no previous wired profile available, wired " + \
|
print("no previous wired profile available, wired " + \
|
||||||
"autoconnect failed."
|
"autoconnect failed.")
|
||||||
self.wireless_bus._wireless_autoconnect(fresh)
|
self.wireless_bus._wireless_autoconnect(fresh)
|
||||||
return
|
return
|
||||||
|
|
||||||
wiredb.ReadWiredNetworkProfile(network)
|
wiredb.ReadWiredNetworkProfile(network)
|
||||||
wiredb.ConnectWired()
|
wiredb.ConnectWired()
|
||||||
print "Attempting to autoconnect with wired interface..."
|
print("Attempting to autoconnect with wired interface...")
|
||||||
self.auto_connecting = True
|
self.auto_connecting = True
|
||||||
time.sleep(1.5)
|
time.sleep(1.5)
|
||||||
try:
|
try:
|
||||||
@@ -818,7 +818,7 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
@dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s')
|
@dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s')
|
||||||
def ConnectResultsSent(self, result):
|
def ConnectResultsSent(self, result):
|
||||||
""" Signal emit when connection results are sent. """
|
""" 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.method("org.wicd.daemon")
|
||||||
@dbus.service.signal(dbus_interface="org.wicd.daemon", signature='')
|
@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='')
|
@dbus.service.signal(dbus_interface='org.wicd.daemon', signature='')
|
||||||
def LaunchChooser(self):
|
def LaunchChooser(self):
|
||||||
""" Emits the wired profile chooser dbus signal. """
|
""" Emits the wired profile chooser dbus signal. """
|
||||||
print 'calling wired profile chooser'
|
print('calling wired profile chooser')
|
||||||
self.SetNeedWiredProfileChooser(True)
|
self.SetNeedWiredProfileChooser(True)
|
||||||
|
|
||||||
@dbus.service.signal(dbus_interface="org.wicd.daemon", signature='')
|
@dbus.service.signal(dbus_interface="org.wicd.daemon", signature='')
|
||||||
@@ -926,38 +926,38 @@ class WicdDaemon(dbus.service.Object, object):
|
|||||||
app_conf.write()
|
app_conf.write()
|
||||||
|
|
||||||
if os.path.isfile(wireless_conf):
|
if os.path.isfile(wireless_conf):
|
||||||
print "Wireless configuration file found..."
|
print("Wireless configuration file found...")
|
||||||
else:
|
else:
|
||||||
print "Wireless configuration file not found, creating..."
|
print("Wireless configuration file not found, creating...")
|
||||||
open(wireless_conf, "w").close()
|
open(wireless_conf, "w").close()
|
||||||
|
|
||||||
if os.path.isfile(wired_conf):
|
if os.path.isfile(wired_conf):
|
||||||
print "Wired configuration file found..."
|
print("Wired configuration file found...")
|
||||||
else:
|
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
|
# Create the file and a default profile
|
||||||
open(wired_conf, "w").close()
|
open(wired_conf, "w").close()
|
||||||
b_wired.CreateWiredNetworkProfile("wired-default", default=True)
|
b_wired.CreateWiredNetworkProfile("wired-default", default=True)
|
||||||
|
|
||||||
if not os.path.isfile(dhclient_conf):
|
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)
|
shutil.copy(dhclient_conf + ".default", dhclient_conf)
|
||||||
# Hide the files, so the keys aren't exposed.
|
# Hide the files, so the keys aren't exposed.
|
||||||
print "chmoding configuration files 0600..."
|
print("chmoding configuration files 0600...")
|
||||||
os.chmod(app_conf.get_config(), 0600)
|
os.chmod(app_conf.get_config(), 0o600)
|
||||||
os.chmod(wireless_conf, 0600)
|
os.chmod(wireless_conf, 0o600)
|
||||||
os.chmod(wired_conf, 0600)
|
os.chmod(wired_conf, 0o600)
|
||||||
os.chmod(dhclient_conf, 0644)
|
os.chmod(dhclient_conf, 0o644)
|
||||||
|
|
||||||
# Make root own them
|
# 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(app_conf.get_config(), 0, 0)
|
||||||
os.chown(wireless_conf, 0, 0)
|
os.chown(wireless_conf, 0, 0)
|
||||||
os.chown(wired_conf, 0, 0)
|
os.chown(wired_conf, 0, 0)
|
||||||
os.chown(dhclient_conf, 0, 0)
|
os.chown(dhclient_conf, 0, 0)
|
||||||
|
|
||||||
print "Using wireless interface..." + self.GetWirelessInterface()
|
print("Using wireless interface..." + self.GetWirelessInterface())
|
||||||
print "Using wired interface..." + self.GetWiredInterface()
|
print("Using wired interface..." + self.GetWiredInterface())
|
||||||
|
|
||||||
##############################
|
##############################
|
||||||
###### Wireless Daemon #######
|
###### Wireless Daemon #######
|
||||||
@@ -1004,10 +1004,10 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
"""
|
"""
|
||||||
if self._scanning:
|
if self._scanning:
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print "scan already in progress, skipping"
|
print("scan already in progress, skipping")
|
||||||
return False
|
return False
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print 'scanning start'
|
print('scanning start')
|
||||||
self.SendStartScanSignal()
|
self.SendStartScanSignal()
|
||||||
if sync:
|
if sync:
|
||||||
self._sync_scan()
|
self._sync_scan()
|
||||||
@@ -1025,8 +1025,8 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
scan = self.wifi.Scan(str(self.hidden_essid))
|
scan = self.wifi.Scan(str(self.hidden_essid))
|
||||||
self.LastScan = scan
|
self.LastScan = scan
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print 'scanning done'
|
print('scanning done')
|
||||||
print 'found ' + str(len(scan)) + ' networks:'
|
print('found ' + str(len(scan)) + ' networks:')
|
||||||
for i, network in enumerate(scan):
|
for i, network in enumerate(scan):
|
||||||
self.ReadWirelessNetworkProfile(i)
|
self.ReadWirelessNetworkProfile(i)
|
||||||
self.SendEndScanSignal()
|
self.SendEndScanSignal()
|
||||||
@@ -1115,8 +1115,8 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
# We don't write script settings here.
|
# We don't write script settings here.
|
||||||
prop = misc.sanitize_config(prop)
|
prop = misc.sanitize_config(prop)
|
||||||
if prop.endswith('script'):
|
if prop.endswith('script'):
|
||||||
print 'Setting script properties through the daemon' \
|
print('Setting script properties through the daemon' \
|
||||||
+ ' is not permitted.'
|
+ ' is not permitted.')
|
||||||
return False
|
return False
|
||||||
# whitelist some props that need different handling
|
# whitelist some props that need different handling
|
||||||
if prop in ('key_index', ):
|
if prop in ('key_index', ):
|
||||||
@@ -1130,9 +1130,9 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
""" Returns an automatically detected wireless interface. """
|
""" Returns an automatically detected wireless interface. """
|
||||||
iface = self.wifi.DetectWirelessInterface()
|
iface = self.wifi.DetectWirelessInterface()
|
||||||
if iface:
|
if iface:
|
||||||
print 'Automatically detected wireless interface ' + iface
|
print('Automatically detected wireless interface ' + iface)
|
||||||
else:
|
else:
|
||||||
print "Couldn't detect a wireless interface."
|
print("Couldn't detect a wireless interface.")
|
||||||
return str(iface)
|
return str(iface)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
@@ -1174,11 +1174,11 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
def GetCurrentNetworkID(self, iwconfig=None):
|
def GetCurrentNetworkID(self, iwconfig=None):
|
||||||
""" Returns the id of the current network, or -1 if its not found. """
|
""" Returns the id of the current network, or -1 if its not found. """
|
||||||
currentESSID = self.GetCurrentNetwork(iwconfig)
|
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:
|
if self.LastScan[x]['essid'] == currentESSID:
|
||||||
return x
|
return x
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print 'GetCurrentNetworkID: Returning -1, current network not found'
|
print('GetCurrentNetworkID: Returning -1, current network not found')
|
||||||
return -1
|
return -1
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@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.bitrate = self.GetWirelessProperty(nid, 'bitrate')
|
||||||
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid,
|
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid,
|
||||||
'allow_lower_bitrates')
|
'allow_lower_bitrates')
|
||||||
print 'Connecting to wireless network ' + \
|
print('Connecting to wireless network ' + \
|
||||||
str(self.LastScan[nid]['essid'])
|
str(self.LastScan[nid]['essid']))
|
||||||
# disconnect to make sure that scripts are run
|
# disconnect to make sure that scripts are run
|
||||||
self.wifi.Disconnect()
|
self.wifi.Disconnect()
|
||||||
self.daemon.wired_bus.wired.Disconnect()
|
self.daemon.wired_bus.wired.Disconnect()
|
||||||
@@ -1265,7 +1265,7 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
return "500: Profile Not Found"
|
return "500: Profile Not Found"
|
||||||
|
|
||||||
for x in self.config.options(section):
|
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))
|
cur_network[x] = misc.Noneify(self.config.get(section, x))
|
||||||
for option in ['use_static_dns', 'use_global_dns', 'encryption',
|
for option in ['use_static_dns', 'use_global_dns', 'encryption',
|
||||||
'use_settings_globally']:
|
'use_settings_globally']:
|
||||||
@@ -1325,8 +1325,8 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
""" Writes a particular wireless property to disk. """
|
""" Writes a particular wireless property to disk. """
|
||||||
option = misc.sanitize_config(option)
|
option = misc.sanitize_config(option)
|
||||||
if option.endswith("script"):
|
if option.endswith("script"):
|
||||||
print 'You cannot save script information to disk through ' + \
|
print('You cannot save script information to disk through ' + \
|
||||||
'the daemon.'
|
'the daemon.')
|
||||||
return
|
return
|
||||||
config = self.config
|
config = self.config
|
||||||
cur_network = self.LastScan[nid]
|
cur_network = self.LastScan[nid]
|
||||||
@@ -1376,8 +1376,8 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
def DeleteWirelessNetwork(self, section):
|
def DeleteWirelessNetwork(self, section):
|
||||||
""" Deletes a wireless network section. """
|
""" Deletes a wireless network section. """
|
||||||
section = misc.to_unicode(section)
|
section = misc.to_unicode(section)
|
||||||
print "Deleting wireless settings for %s (%s)" % \
|
print("Deleting wireless settings for %s (%s)" % \
|
||||||
(self.config.get(section, 'essid'), str(section))
|
(self.config.get(section, 'essid'), str(section)))
|
||||||
self.config.remove_section(section)
|
self.config.remove_section(section)
|
||||||
self.config.write()
|
self.config.write()
|
||||||
|
|
||||||
@@ -1395,10 +1395,10 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
|
|
||||||
def _wireless_autoconnect(self, fresh=True):
|
def _wireless_autoconnect(self, fresh=True):
|
||||||
""" Attempts to autoconnect to a wireless network. """
|
""" Attempts to autoconnect to a wireless network. """
|
||||||
print "No wired connection present, attempting to autoconnect " + \
|
print("No wired connection present, attempting to autoconnect " + \
|
||||||
"to wireless network"
|
"to wireless network")
|
||||||
if self.wifi.wireless_interface is None:
|
if self.wifi.wireless_interface is None:
|
||||||
print 'Autoconnect failed because wireless interface returned None'
|
print('Autoconnect failed because wireless interface returned None')
|
||||||
return
|
return
|
||||||
if fresh:
|
if fresh:
|
||||||
self.Scan(sync=True)
|
self.Scan(sync=True)
|
||||||
@@ -1406,19 +1406,19 @@ class WirelessDaemon(dbus.service.Object, object):
|
|||||||
for x, network in enumerate(self.LastScan):
|
for x, network in enumerate(self.LastScan):
|
||||||
if self.config.has_section(network['bssid']):
|
if self.config.has_section(network['bssid']):
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print network["essid"] + ' has profile'
|
print(network["essid"] + ' has profile')
|
||||||
if bool(network.get('automatic')):
|
if bool(network.get('automatic')):
|
||||||
if network.get('never'):
|
if network.get('never'):
|
||||||
print network["essid"],'marked never connect'
|
print(network["essid"],'marked never connect')
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
print network["essid"],'has no never connect value'
|
print(network["essid"],'has no never connect value')
|
||||||
print 'trying to automatically connect to...' + \
|
print('trying to automatically connect to...' + \
|
||||||
network["essid"]
|
network["essid"])
|
||||||
self.ConnectWireless(x)
|
self.ConnectWireless(x)
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
return
|
return
|
||||||
print "Unable to autoconnect, you'll have to manually connect"
|
print("Unable to autoconnect, you'll have to manually connect")
|
||||||
|
|
||||||
###########################
|
###########################
|
||||||
###### Wired Daemon #######
|
###### Wired Daemon #######
|
||||||
@@ -1481,9 +1481,9 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
""" Returns an automatically detected wireless interface. """
|
""" Returns an automatically detected wireless interface. """
|
||||||
iface = self.wired.DetectWiredInterface()
|
iface = self.wired.DetectWiredInterface()
|
||||||
if iface:
|
if iface:
|
||||||
print 'automatically detected wired interface ' + str(iface)
|
print('automatically detected wired interface ' + str(iface))
|
||||||
else:
|
else:
|
||||||
print "Couldn't detect a wired interface."
|
print("Couldn't detect a wired interface.")
|
||||||
return str(iface)
|
return str(iface)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wired')
|
@dbus.service.method('org.wicd.daemon.wired')
|
||||||
@@ -1492,13 +1492,13 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
if self.WiredNetwork:
|
if self.WiredNetwork:
|
||||||
prop = misc.sanitize_config(prop)
|
prop = misc.sanitize_config(prop)
|
||||||
if prop.endswith('script'):
|
if prop.endswith('script'):
|
||||||
print 'Setting script properties through the daemon' \
|
print('Setting script properties through the daemon' \
|
||||||
+ ' is not permitted.'
|
+ ' is not permitted.')
|
||||||
return False
|
return False
|
||||||
self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value))
|
self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value))
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
print 'SetWiredProperty: WiredNetwork does not exist'
|
print('SetWiredProperty: WiredNetwork does not exist')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wired')
|
@dbus.service.method('org.wicd.daemon.wired')
|
||||||
@@ -1508,7 +1508,7 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
value = self.WiredNetwork.get(prop)
|
value = self.WiredNetwork.get(prop)
|
||||||
return value
|
return value
|
||||||
else:
|
else:
|
||||||
print 'GetWiredProperty: WiredNetwork does not exist'
|
print('GetWiredProperty: WiredNetwork does not exist')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wired')
|
@dbus.service.method('org.wicd.daemon.wired')
|
||||||
@@ -1572,7 +1572,7 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
if not profilename:
|
if not profilename:
|
||||||
return False
|
return False
|
||||||
profilename = misc.to_unicode(profilename)
|
profilename = misc.to_unicode(profilename)
|
||||||
print "Creating wired profile for " + profilename
|
print("Creating wired profile for " + profilename)
|
||||||
if self.config.has_section(profilename):
|
if self.config.has_section(profilename):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -1624,7 +1624,7 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
def DeleteWiredNetworkProfile(self, profilename):
|
def DeleteWiredNetworkProfile(self, profilename):
|
||||||
""" Deletes a wired network profile. """
|
""" Deletes a wired network profile. """
|
||||||
profilename = misc.to_unicode(profilename)
|
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.remove_section(profilename)
|
||||||
self.config.write()
|
self.config.write()
|
||||||
|
|
||||||
@@ -1638,10 +1638,10 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
profilename = profilename.strip()
|
profilename = profilename.strip()
|
||||||
if not profilename:
|
if not profilename:
|
||||||
self.config.write()
|
self.config.write()
|
||||||
print "Warning: Bad wired profile name given, ignoring."
|
print("Warning: Bad wired profile name given, ignoring.")
|
||||||
return "500: Bad Profile name"
|
return "500: Bad Profile name"
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print "saving wired profile %s" % profilename
|
print("saving wired profile %s" % profilename)
|
||||||
profilename = misc.to_unicode(profilename)
|
profilename = misc.to_unicode(profilename)
|
||||||
self.config.remove_section(profilename)
|
self.config.remove_section(profilename)
|
||||||
self.config.add_section(profilename)
|
self.config.add_section(profilename)
|
||||||
@@ -1662,7 +1662,7 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
profilename = misc.to_unicode(profilename)
|
profilename = misc.to_unicode(profilename)
|
||||||
if self.config.has_section(profilename):
|
if self.config.has_section(profilename):
|
||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print "Reading wired profile %s" % profilename
|
print("Reading wired profile %s" % profilename)
|
||||||
for x in self.config.options(profilename):
|
for x in self.config.options(profilename):
|
||||||
profile[x] = misc.Noneify(self.config.get(profilename, x))
|
profile[x] = misc.Noneify(self.config.get(profilename, x))
|
||||||
profile['use_global_dns'] = bool(profile.get('use_global_dns'))
|
profile['use_global_dns'] = bool(profile.get('use_global_dns'))
|
||||||
@@ -1698,7 +1698,7 @@ class WiredDaemon(dbus.service.Object, object):
|
|||||||
|
|
||||||
def usage():
|
def usage():
|
||||||
""" Print help screen. """
|
""" Print help screen. """
|
||||||
print """
|
print("""
|
||||||
wicd %s
|
wicd %s
|
||||||
wireless (and wired) connection daemon.
|
wireless (and wired) connection daemon.
|
||||||
|
|
||||||
@@ -1710,7 +1710,7 @@ Arguments:
|
|||||||
\t-n\t--no-poll\tDon't monitor network status.
|
\t-n\t--no-poll\tDon't monitor network status.
|
||||||
\t-o\t--no-stdout\tDon't redirect stdout.
|
\t-o\t--no-stdout\tDon't redirect stdout.
|
||||||
\t-h\t--help\t\tPrint this help.
|
\t-h\t--help\t\tPrint this help.
|
||||||
""" % (wpath.version + ' (bzr-r%s)' % wpath.revision)
|
""" % (wpath.version + ' (bzr-r%s)' % wpath.revision))
|
||||||
|
|
||||||
def daemonize():
|
def daemonize():
|
||||||
""" Disconnect from the controlling terminal.
|
""" Disconnect from the controlling terminal.
|
||||||
@@ -1729,8 +1729,8 @@ def daemonize():
|
|||||||
pid = os.fork()
|
pid = os.fork()
|
||||||
if pid > 0:
|
if pid > 0:
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
except OSError, e:
|
except OSError as e:
|
||||||
print >> sys.stderr, "Fork #1 failed: %d (%s)" % (e.errno, e.strerror)
|
print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Decouple from parent environment to stop us from being a zombie.
|
# Decouple from parent environment to stop us from being a zombie.
|
||||||
@@ -1751,8 +1751,8 @@ def daemonize():
|
|||||||
else:
|
else:
|
||||||
os.umask(0)
|
os.umask(0)
|
||||||
os.chdir('/')
|
os.chdir('/')
|
||||||
except OSError, e:
|
except OSError as e:
|
||||||
print >> sys.stderr, "Fork #2 failed: %d (%s)" % (e.errno, e.strerror)
|
print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
sys.stdin.close()
|
sys.stdin.close()
|
||||||
@@ -1795,9 +1795,9 @@ def main(argv):
|
|||||||
os.symlink(dest, backup_location)
|
os.symlink(dest, backup_location)
|
||||||
else:
|
else:
|
||||||
shutil.copy2('/etc/resolv.conf', backup_location)
|
shutil.copy2('/etc/resolv.conf', backup_location)
|
||||||
os.chmod(backup_location, 0644)
|
os.chmod(backup_location, 0o644)
|
||||||
except IOError:
|
except IOError:
|
||||||
print 'error backing up resolv.conf'
|
print('error backing up resolv.conf')
|
||||||
|
|
||||||
do_daemonize = True
|
do_daemonize = True
|
||||||
redirect_stderr = True
|
redirect_stderr = True
|
||||||
@@ -1852,9 +1852,9 @@ def main(argv):
|
|||||||
os.symlink(dest, '/etc/resolv.conf')
|
os.symlink(dest, '/etc/resolv.conf')
|
||||||
else:
|
else:
|
||||||
shutil.move(backup_location, '/etc/resolv.conf')
|
shutil.move(backup_location, '/etc/resolv.conf')
|
||||||
os.chmod('/etc/resolv.conf', 0644)
|
os.chmod('/etc/resolv.conf', 0o644)
|
||||||
except IOError:
|
except IOError:
|
||||||
print 'error restoring resolv.conf'
|
print('error restoring resolv.conf')
|
||||||
|
|
||||||
# connect to dbus, trigger a disconnect, then knock out the daemon
|
# connect to dbus, trigger a disconnect, then knock out the daemon
|
||||||
from wicd import dbusmanager
|
from wicd import dbusmanager
|
||||||
@@ -1869,8 +1869,8 @@ def main(argv):
|
|||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
if os.path.exists(wpath.pidfile):
|
if os.path.exists(wpath.pidfile):
|
||||||
print 'It seems like the daemon is already running.'
|
print('It seems like the daemon is already running.')
|
||||||
print 'If it is not, please remove %s and try again.' % wpath.pidfile
|
print('If it is not, please remove %s and try again.' % wpath.pidfile)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
if not os.path.exists(wpath.networks):
|
if not os.path.exists(wpath.networks):
|
||||||
@@ -1883,13 +1883,13 @@ def main(argv):
|
|||||||
logpath = os.path.join(wpath.log, 'wicd.log')
|
logpath = os.path.join(wpath.log, 'wicd.log')
|
||||||
if not os.path.exists(wpath.log):
|
if not os.path.exists(wpath.log):
|
||||||
os.makedirs(wpath.log)
|
os.makedirs(wpath.log)
|
||||||
os.chmod(wpath.log, 0755)
|
os.chmod(wpath.log, 0o755)
|
||||||
output = ManagedStdio(logpath)
|
output = ManagedStdio(logpath)
|
||||||
if os.path.exists(logpath):
|
if os.path.exists(logpath):
|
||||||
try:
|
try:
|
||||||
os.chmod(logpath, int(wpath.log_perms, 8))
|
os.chmod(logpath, int(wpath.log_perms, 8))
|
||||||
except OSError:
|
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:
|
try:
|
||||||
if wpath.log_group:
|
if wpath.log_group:
|
||||||
@@ -1897,18 +1897,18 @@ def main(argv):
|
|||||||
group = grp.getgrnam(wpath.log_group)
|
group = grp.getgrnam(wpath.log_group)
|
||||||
os.chown(logpath, 0, group[2])
|
os.chown(logpath, 0, group[2])
|
||||||
except OSError:
|
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:
|
if redirect_stdout:
|
||||||
sys.stdout = output
|
sys.stdout = output
|
||||||
if redirect_stderr:
|
if redirect_stderr:
|
||||||
sys.stderr = output
|
sys.stderr = output
|
||||||
|
|
||||||
print '---------------------------'
|
print('---------------------------')
|
||||||
print 'wicd initializing...'
|
print('wicd initializing...')
|
||||||
print '---------------------------'
|
print('---------------------------')
|
||||||
|
|
||||||
print 'wicd is version', wpath.version, wpath.revision
|
print('wicd is version', wpath.version, wpath.revision)
|
||||||
|
|
||||||
# Open the DBUS session
|
# Open the DBUS session
|
||||||
bus = dbus.SystemBus()
|
bus = dbus.SystemBus()
|
||||||
@@ -1933,22 +1933,22 @@ def main(argv):
|
|||||||
def on_exit(child_pid):
|
def on_exit(child_pid):
|
||||||
""" Called when a SIGTERM is caught, kills monitor.py before exiting. """
|
""" Called when a SIGTERM is caught, kills monitor.py before exiting. """
|
||||||
if child_pid:
|
if child_pid:
|
||||||
print 'Daemon going down, killing wicd-monitor...'
|
print('Daemon going down, killing wicd-monitor...')
|
||||||
try:
|
try:
|
||||||
os.kill(child_pid, signal.SIGTERM)
|
os.kill(child_pid, signal.SIGTERM)
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
print 'Removing PID file...'
|
print('Removing PID file...')
|
||||||
if os.path.exists(wpath.pidfile):
|
if os.path.exists(wpath.pidfile):
|
||||||
os.remove(wpath.pidfile)
|
os.remove(wpath.pidfile)
|
||||||
print 'Shutting down...'
|
print('Shutting down...')
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if os.getuid() != 0:
|
if os.getuid() != 0:
|
||||||
print ("Root privileges are required for the daemon to run properly." +
|
print(("Root privileges are required for the daemon to run properly." +
|
||||||
" Exiting.")
|
" Exiting."))
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
gobject.threads_init()
|
gobject.threads_init()
|
||||||
main(sys.argv)
|
main(sys.argv)
|
||||||
|
|||||||
@@ -41,8 +41,8 @@ import socket, fcntl
|
|||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
import wpath
|
import wpath
|
||||||
import misc
|
from . import misc
|
||||||
from misc import find_path
|
from .misc import find_path
|
||||||
|
|
||||||
# Regular expressions.
|
# Regular expressions.
|
||||||
_re_mode = (re.I | re.M | re.S)
|
_re_mode = (re.I | re.M | re.S)
|
||||||
@@ -129,7 +129,7 @@ def GetDefaultGateway():
|
|||||||
gateway = None
|
gateway = None
|
||||||
for line in lines:
|
for line in lines:
|
||||||
words = line.split()
|
words = line.split()
|
||||||
print words
|
print(words)
|
||||||
if not words:
|
if not words:
|
||||||
continue
|
continue
|
||||||
if words[0] == '0.0.0.0':
|
if words[0] == '0.0.0.0':
|
||||||
@@ -137,7 +137,7 @@ def GetDefaultGateway():
|
|||||||
break
|
break
|
||||||
|
|
||||||
if not gateway:
|
if not gateway:
|
||||||
print 'couldn\'t retrieve default gateway from route -n'
|
print('couldn\'t retrieve default gateway from route -n')
|
||||||
return gateway
|
return gateway
|
||||||
|
|
||||||
def isWireless(devname):
|
def isWireless(devname):
|
||||||
@@ -196,7 +196,7 @@ def GetWpaSupplicantDrivers():
|
|||||||
try:
|
try:
|
||||||
output = output.split("drivers:")[1].split("options:")[0].strip()
|
output = output.split("drivers:")[1].split("options:")[0].strip()
|
||||||
except KeyError:
|
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 [""]
|
return [""]
|
||||||
patt = re.compile("(\S+)\s+=.*")
|
patt = re.compile("(\S+)\s+=.*")
|
||||||
drivers = patt.findall(output) or [""]
|
drivers = patt.findall(output) or [""]
|
||||||
@@ -292,7 +292,7 @@ class BaseInterface(object):
|
|||||||
"""
|
"""
|
||||||
path = find_path(program)
|
path = find_path(program)
|
||||||
if not path and self.verbose:
|
if not path and self.verbose:
|
||||||
print "WARNING: No path found for %s" % program
|
print("WARNING: No path found for %s" % program)
|
||||||
return path
|
return path
|
||||||
|
|
||||||
|
|
||||||
@@ -363,8 +363,8 @@ class BaseInterface(object):
|
|||||||
# for specifing the hostname to be sent
|
# for specifing the hostname to be sent
|
||||||
if client_name == "dhclient" and flavor:
|
if client_name == "dhclient" and flavor:
|
||||||
if hostname:
|
if hostname:
|
||||||
print 'attempting to set hostname with dhclient'
|
print('attempting to set hostname with dhclient')
|
||||||
print 'using dhcpcd or another supported client may work better'
|
print('using dhcpcd or another supported client may work better')
|
||||||
|
|
||||||
dhclient_template = \
|
dhclient_template = \
|
||||||
open(os.path.join(wpath.etc, 'dhclient.conf.template'), 'r')
|
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'), \
|
shutil.copy(os.path.join(wpath.etc, 'dhclient.conf.template'), \
|
||||||
dhclient_conf_path)
|
dhclient_conf_path)
|
||||||
|
|
||||||
os.chmod(dhclient_conf_path, 0644)
|
os.chmod(dhclient_conf_path, 0o644)
|
||||||
|
|
||||||
if not client_name or not cmd:
|
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 ""
|
return ""
|
||||||
|
|
||||||
if flavor == "connect":
|
if flavor == "connect":
|
||||||
@@ -468,7 +468,7 @@ class BaseInterface(object):
|
|||||||
""" Check for the existence of wpa_cli """
|
""" Check for the existence of wpa_cli """
|
||||||
self.wpa_cli_cmd = self._find_program_path("wpa_cli")
|
self.wpa_cli_cmd = self._find_program_path("wpa_cli")
|
||||||
if not self.wpa_cli_cmd:
|
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):
|
def CheckRouteFlushTool(self):
|
||||||
""" Check for a route flush tool. """
|
""" Check for a route flush tool. """
|
||||||
@@ -491,7 +491,7 @@ class BaseInterface(object):
|
|||||||
"""
|
"""
|
||||||
cmd = 'ifconfig ' + self.iface + ' up'
|
cmd = 'ifconfig ' + self.iface + ' up'
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -505,7 +505,7 @@ class BaseInterface(object):
|
|||||||
"""
|
"""
|
||||||
cmd = 'ifconfig ' + self.iface + ' down'
|
cmd = 'ifconfig ' + self.iface + ' down'
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -515,7 +515,7 @@ class BaseInterface(object):
|
|||||||
""" Runs ifconfig and returns the output. """
|
""" Runs ifconfig and returns the output. """
|
||||||
cmd = "ifconfig %s" % self.iface
|
cmd = "ifconfig %s" % self.iface
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
return misc.Run(cmd)
|
return misc.Run(cmd)
|
||||||
|
|
||||||
@neediface("")
|
@neediface("")
|
||||||
@@ -532,7 +532,7 @@ class BaseInterface(object):
|
|||||||
if not val:
|
if not val:
|
||||||
continue
|
continue
|
||||||
if not misc.IsValidIP(val):
|
if not misc.IsValidIP(val):
|
||||||
print 'WARNING: Invalid IP address found, aborting!'
|
print('WARNING: Invalid IP address found, aborting!')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
cmd = ''.join(['ifconfig ', self.iface, ' '])
|
cmd = ''.join(['ifconfig ', self.iface, ' '])
|
||||||
@@ -543,7 +543,7 @@ class BaseInterface(object):
|
|||||||
if broadcast:
|
if broadcast:
|
||||||
cmd = ''.join([cmd, 'broadcast ', broadcast, ' '])
|
cmd = ''.join([cmd, 'broadcast ', broadcast, ' '])
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
def _parse_dhclient(self, pipe):
|
def _parse_dhclient(self, pipe):
|
||||||
@@ -567,7 +567,7 @@ class BaseInterface(object):
|
|||||||
if line == '': # Empty string means dhclient is done.
|
if line == '': # Empty string means dhclient is done.
|
||||||
dhclient_complete = True
|
dhclient_complete = True
|
||||||
else:
|
else:
|
||||||
print misc.to_unicode(line.strip('\n'))
|
print(misc.to_unicode(line.strip('\n')))
|
||||||
if line.startswith('bound'):
|
if line.startswith('bound'):
|
||||||
dhclient_success = True
|
dhclient_success = True
|
||||||
dhclient_complete = True
|
dhclient_complete = True
|
||||||
@@ -594,7 +594,7 @@ class BaseInterface(object):
|
|||||||
elif line.strip().lower().startswith('Operation failed.'):
|
elif line.strip().lower().startswith('Operation failed.'):
|
||||||
pump_success = False
|
pump_success = False
|
||||||
pump_complete = True
|
pump_complete = True
|
||||||
print misc.to_unicode(line)
|
print(misc.to_unicode(line))
|
||||||
|
|
||||||
return self._check_dhcp_result(pump_success)
|
return self._check_dhcp_result(pump_success)
|
||||||
|
|
||||||
@@ -618,7 +618,7 @@ class BaseInterface(object):
|
|||||||
dhcpcd_complete = True
|
dhcpcd_complete = True
|
||||||
elif line == '':
|
elif line == '':
|
||||||
dhcpcd_complete = True
|
dhcpcd_complete = True
|
||||||
print misc.to_unicode(line)
|
print(misc.to_unicode(line))
|
||||||
|
|
||||||
return self._check_dhcp_result(dhcpcd_success)
|
return self._check_dhcp_result(dhcpcd_success)
|
||||||
|
|
||||||
@@ -642,7 +642,7 @@ class BaseInterface(object):
|
|||||||
udhcpc_complete = True
|
udhcpc_complete = True
|
||||||
elif line == '':
|
elif line == '':
|
||||||
udhcpc_complete = True
|
udhcpc_complete = True
|
||||||
print line
|
print(line)
|
||||||
|
|
||||||
return self._check_dhcp_result(udhcpc_success)
|
return self._check_dhcp_result(udhcpc_success)
|
||||||
|
|
||||||
@@ -657,10 +657,10 @@ class BaseInterface(object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
if success:
|
if success:
|
||||||
print 'DHCP connection successful'
|
print('DHCP connection successful')
|
||||||
return 'success'
|
return 'success'
|
||||||
else:
|
else:
|
||||||
print 'DHCP connection failed'
|
print('DHCP connection failed')
|
||||||
return 'dhcp_failed'
|
return 'dhcp_failed'
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -677,7 +677,7 @@ class BaseInterface(object):
|
|||||||
"""
|
"""
|
||||||
cmd = self._get_dhcp_command('connect', hostname, staticdns)
|
cmd = self._get_dhcp_command('connect', hostname, staticdns)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
|
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
|
||||||
pipe = self.dhcp_object.stdout
|
pipe = self.dhcp_object.stdout
|
||||||
client_dict = { misc.DHCLIENT : self._parse_dhclient,
|
client_dict = { misc.DHCLIENT : self._parse_dhclient,
|
||||||
@@ -690,7 +690,7 @@ class BaseInterface(object):
|
|||||||
if DHCP_CLIENT in client_dict:
|
if DHCP_CLIENT in client_dict:
|
||||||
ret = client_dict[DHCP_CLIENT](pipe)
|
ret = client_dict[DHCP_CLIENT](pipe)
|
||||||
else:
|
else:
|
||||||
print "ERROR: no dhcp client found"
|
print("ERROR: no dhcp client found")
|
||||||
ret = None
|
ret = None
|
||||||
self.dhcp_object.wait()
|
self.dhcp_object.wait()
|
||||||
return ret
|
return ret
|
||||||
@@ -700,7 +700,7 @@ class BaseInterface(object):
|
|||||||
""" Release the DHCP lease for this interface. """
|
""" Release the DHCP lease for this interface. """
|
||||||
cmd = self._get_dhcp_command("release")
|
cmd = self._get_dhcp_command("release")
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -711,10 +711,10 @@ class BaseInterface(object):
|
|||||||
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
|
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
|
||||||
cmd = '%s del default dev %s' % (self.route_cmd, self.iface)
|
cmd = '%s del default dev %s' % (self.route_cmd, self.iface)
|
||||||
else:
|
else:
|
||||||
print "No route manipulation command available!"
|
print("No route manipulation command available!")
|
||||||
return
|
return
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -727,7 +727,7 @@ class BaseInterface(object):
|
|||||||
if self.resolvconf_cmd:
|
if self.resolvconf_cmd:
|
||||||
cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd']
|
cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd']
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
||||||
p.communicate()
|
p.communicate()
|
||||||
|
|
||||||
@@ -757,10 +757,10 @@ class BaseInterface(object):
|
|||||||
if dns:
|
if dns:
|
||||||
if misc.IsValidIP(dns):
|
if misc.IsValidIP(dns):
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print 'Setting DNS : ' + dns
|
print('Setting DNS : ' + dns)
|
||||||
valid_dns_list.append("nameserver %s\n" % dns)
|
valid_dns_list.append("nameserver %s\n" % dns)
|
||||||
else:
|
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:
|
if valid_dns_list:
|
||||||
resolv_params += ''.join(valid_dns_list)
|
resolv_params += ''.join(valid_dns_list)
|
||||||
@@ -768,7 +768,7 @@ class BaseInterface(object):
|
|||||||
if self.resolvconf_cmd:
|
if self.resolvconf_cmd:
|
||||||
cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd']
|
cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd']
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
||||||
p.communicate(input=resolv_params)
|
p.communicate(input=resolv_params)
|
||||||
else:
|
else:
|
||||||
@@ -784,11 +784,11 @@ class BaseInterface(object):
|
|||||||
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
|
elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]:
|
||||||
cmds = ['%s del dev %s' % (self.route_cmd, self.iface)]
|
cmds = ['%s del dev %s' % (self.route_cmd, self.iface)]
|
||||||
else:
|
else:
|
||||||
print "No flush command available!"
|
print("No flush command available!")
|
||||||
cmds = []
|
cmds = []
|
||||||
for cmd in cmds:
|
for cmd in cmds:
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -800,11 +800,11 @@ class BaseInterface(object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
if not misc.IsValidIP(gw):
|
if not misc.IsValidIP(gw):
|
||||||
print 'WARNING: Invalid gateway found. Aborting!'
|
print('WARNING: Invalid gateway found. Aborting!')
|
||||||
return False
|
return False
|
||||||
cmd = 'route add default gw %s dev %s' % (gw, self.iface)
|
cmd = 'route add default gw %s dev %s' % (gw, self.iface)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface("")
|
@neediface("")
|
||||||
@@ -845,7 +845,7 @@ class BaseInterface(object):
|
|||||||
# most.
|
# most.
|
||||||
cmd = "ping -q -c 1 %s" % gateway
|
cmd = "ping -q -c 1 %s" % gateway
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
return misc.LaunchAndWait(cmd)
|
return misc.LaunchAndWait(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -860,8 +860,8 @@ class BaseInterface(object):
|
|||||||
try:
|
try:
|
||||||
flags = open(flags_file, "r").read().strip()
|
flags = open(flags_file, "r").read().strip()
|
||||||
except IOError:
|
except IOError:
|
||||||
print "Could not open %s, using ifconfig to determine status" \
|
print("Could not open %s, using ifconfig to determine status" \
|
||||||
% flags_file
|
% flags_file)
|
||||||
return self._slow_is_up(ifconfig)
|
return self._slow_is_up(ifconfig)
|
||||||
return bool(int(flags, 16) & 1)
|
return bool(int(flags, 16) & 1)
|
||||||
|
|
||||||
@@ -870,7 +870,7 @@ class BaseInterface(object):
|
|||||||
""" Terminates wpa using wpa_cli"""
|
""" Terminates wpa using wpa_cli"""
|
||||||
cmd = 'wpa_cli -i %s terminate' % self.iface
|
cmd = 'wpa_cli -i %s terminate' % self.iface
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
|
|
||||||
@@ -942,16 +942,16 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
elif link == 0:
|
elif link == 0:
|
||||||
return False
|
return False
|
||||||
except (IOError, ValueError, TypeError):
|
except (IOError, ValueError, TypeError):
|
||||||
print 'Error checking link using /sys/class/net/%s/carrier' \
|
print('Error checking link using /sys/class/net/%s/carrier' \
|
||||||
% self.iface
|
% self.iface)
|
||||||
|
|
||||||
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
|
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
|
||||||
return self._eth_get_plugged_in()
|
return self._eth_get_plugged_in()
|
||||||
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
|
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
|
||||||
return self._mii_get_plugged_in()
|
return self._mii_get_plugged_in()
|
||||||
else:
|
else:
|
||||||
print ('Error: No way of checking for a wired connection. Make ' +
|
print(('Error: No way of checking for a wired connection. Make ' +
|
||||||
'sure that either mii-tool or ethtool is installed.')
|
'sure that either mii-tool or ethtool is installed.'))
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _eth_get_plugged_in(self):
|
def _eth_get_plugged_in(self):
|
||||||
@@ -963,11 +963,11 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
"""
|
"""
|
||||||
cmd = "%s %s" % (self.ethtool_cmd, self.iface)
|
cmd = "%s %s" % (self.ethtool_cmd, self.iface)
|
||||||
if not self.IsUp():
|
if not self.IsUp():
|
||||||
print 'Wired Interface is down, putting it up'
|
print('Wired Interface is down, putting it up')
|
||||||
self.Up()
|
self.Up()
|
||||||
time.sleep(6)
|
time.sleep(6)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
tool_data = misc.Run(cmd, include_stderr=True)
|
tool_data = misc.Run(cmd, include_stderr=True)
|
||||||
if misc.RunRegex(
|
if misc.RunRegex(
|
||||||
re.compile('(Link detected: yes)', re.I | re.M | re.S),
|
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)
|
cmd = "%s %s" % (self.miitool_cmd, self.iface)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
tool_data = misc.Run(cmd, include_stderr=True)
|
tool_data = misc.Run(cmd, include_stderr=True)
|
||||||
if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S),
|
if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S),
|
||||||
tool_data) is not None:
|
tool_data) is not None:
|
||||||
print 'Wired Interface is down, putting it up'
|
print('Wired Interface is down, putting it up')
|
||||||
self.Up()
|
self.Up()
|
||||||
time.sleep(4)
|
time.sleep(4)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
tool_data = misc.Run(cmd, include_stderr=True)
|
tool_data = misc.Run(cmd, include_stderr=True)
|
||||||
|
|
||||||
if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S),
|
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'),
|
os.path.join(wpath.networks, 'wired'),
|
||||||
'-Dwired']
|
'-Dwired']
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
class BaseWirelessInterface(BaseInterface):
|
class BaseWirelessInterface(BaseInterface):
|
||||||
@@ -1041,7 +1041,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
"""
|
"""
|
||||||
cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)]
|
cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)]
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print str(cmd)
|
print(str(cmd))
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1068,7 +1068,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
""" Returns the output of iwconfig for this interface. """
|
""" Returns the output of iwconfig for this interface. """
|
||||||
cmd = "iwconfig " + self.iface
|
cmd = "iwconfig " + self.iface
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
return misc.Run(cmd)
|
return misc.Run(cmd)
|
||||||
|
|
||||||
def _FreqToChannel(self, freq):
|
def _FreqToChannel(self, freq):
|
||||||
@@ -1093,7 +1093,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
try:
|
try:
|
||||||
ret = freq_dict[freq]
|
ret = freq_dict[freq]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print "Couldn't determine channel number for frequency:", str(freq)
|
print("Couldn't determine channel number for frequency:", str(freq))
|
||||||
|
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
@@ -1107,7 +1107,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
"""
|
"""
|
||||||
iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey')
|
iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey')
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print iwpriv
|
print(iwpriv)
|
||||||
lines = iwpriv.splitlines()[2:]
|
lines = iwpriv.splitlines()[2:]
|
||||||
aps = {}
|
aps = {}
|
||||||
patt = re.compile("((?:[0-9A-Z]{2}:){5}[0-9A-Z]{2})")
|
patt = re.compile("((?:[0-9A-Z]{2}:){5}[0-9A-Z]{2})")
|
||||||
@@ -1124,7 +1124,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
bssid = info[3].upper()
|
bssid = info[3].upper()
|
||||||
offset = 0
|
offset = 0
|
||||||
else: # Invalid
|
else: # Invalid
|
||||||
print 'Invalid iwpriv line. Skipping it.'
|
print('Invalid iwpriv line. Skipping it.')
|
||||||
continue
|
continue
|
||||||
ap['nettype'] = info[-1]
|
ap['nettype'] = info[-1]
|
||||||
ap['strength'] = info[1]
|
ap['strength'] = info[1]
|
||||||
@@ -1146,11 +1146,11 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
elif info[4 + offset] == "NONE":
|
elif info[4 + offset] == "NONE":
|
||||||
ap['encryption_method'] = None
|
ap['encryption_method'] = None
|
||||||
else:
|
else:
|
||||||
print "Unknown AuthMode, can't assign encryption_method!"
|
print("Unknown AuthMode, can't assign encryption_method!")
|
||||||
ap['encryption_method'] = 'Unknown'
|
ap['encryption_method'] = 'Unknown'
|
||||||
aps[bssid] = ap
|
aps[bssid] = ap
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print str(aps)
|
print(str(aps))
|
||||||
return aps
|
return aps
|
||||||
|
|
||||||
def _ParseRalinkAccessPoint(self, ap, ralink_info, cell):
|
def _ParseRalinkAccessPoint(self, ap, ralink_info, cell):
|
||||||
@@ -1165,9 +1165,9 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
Updated array containing info about the current access point
|
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']]
|
info = ralink_info[ap['bssid']]
|
||||||
for key in info.keys():
|
for key in list(info.keys()):
|
||||||
ap[key] = info[key]
|
ap[key] = info[key]
|
||||||
if misc.RunRegex(wep_pattern, cell) == 'on':
|
if misc.RunRegex(wep_pattern, cell) == 'on':
|
||||||
ap['encryption'] = True
|
ap['encryption'] = True
|
||||||
@@ -1190,7 +1190,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
mode = 'managed'
|
mode = 'managed'
|
||||||
cmd = 'iwconfig %s mode %s' % (self.iface, mode)
|
cmd = 'iwconfig %s mode %s' % (self.iface, mode)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1202,12 +1202,12 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
if not channel.isdigit():
|
if not channel.isdigit():
|
||||||
print 'WARNING: Invalid channel found. Aborting!'
|
print('WARNING: Invalid channel found. Aborting!')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
cmd = 'iwconfig %s channel %s' % (self.iface, str(channel))
|
cmd = 'iwconfig %s channel %s' % (self.iface, str(channel))
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1220,7 +1220,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
"""
|
"""
|
||||||
cmd = 'iwconfig %s key %s' % (self.iface, key)
|
cmd = 'iwconfig %s key %s' % (self.iface, key)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1257,12 +1257,12 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
if channel and str(channel).isdigit():
|
if channel and str(channel).isdigit():
|
||||||
cmd = "%s channel %s" % (base, str(channel))
|
cmd = "%s channel %s" % (base, str(channel))
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
if bssid:
|
if bssid:
|
||||||
cmd = "%s ap %s" % (base, bssid)
|
cmd = "%s ap %s" % (base, bssid)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
def GeneratePSK(self, network):
|
def GeneratePSK(self, network):
|
||||||
@@ -1279,7 +1279,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
re.I | re.M | re.S)
|
re.I | re.M | re.S)
|
||||||
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
|
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
return misc.RunRegex(key_pattern, misc.Run(cmd))
|
return misc.RunRegex(key_pattern, misc.Run(cmd))
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1303,7 +1303,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
network['bssid'].replace(':', '').lower()),
|
network['bssid'].replace(':', '').lower()),
|
||||||
driver]
|
driver]
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
def _AuthenticateRalinkLegacy(self, network):
|
def _AuthenticateRalinkLegacy(self, network):
|
||||||
@@ -1320,16 +1320,16 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
try:
|
try:
|
||||||
info = self._GetRalinkInfo()[network.get('bssid')]
|
info = self._GetRalinkInfo()[network.get('bssid')]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print "Could not find current network in iwpriv " + \
|
print("Could not find current network in iwpriv " + \
|
||||||
"get_site_survey results. Cannot authenticate."
|
"get_site_survey results. Cannot authenticate.")
|
||||||
return
|
return
|
||||||
|
|
||||||
if info['enctype'] == "WEP" and info['authtype'] == 'OPEN':
|
if info['enctype'] == "WEP" and info['authtype'] == 'OPEN':
|
||||||
print 'Setting up WEP'
|
print('Setting up WEP')
|
||||||
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
||||||
network.get('key')])
|
network.get('key')])
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
else:
|
else:
|
||||||
cmd_list = []
|
cmd_list = []
|
||||||
@@ -1344,7 +1344,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
for cmd in cmd_list:
|
for cmd in cmd_list:
|
||||||
cmd = ['iwpriv', self.iface, 'set', cmd]
|
cmd = ['iwpriv', self.iface, 'set', cmd]
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print ' '.join(cmd)
|
print(' '.join(cmd))
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface([])
|
@neediface([])
|
||||||
@@ -1362,11 +1362,11 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
# but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan.
|
# but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan.
|
||||||
essid = misc.Noneify(essid)
|
essid = misc.Noneify(essid)
|
||||||
if essid is not None:
|
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
|
cmd = cmd + ' essid ' + essid
|
||||||
|
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
results = misc.Run(cmd)
|
results = misc.Run(cmd)
|
||||||
# Split the networks apart, using Cell as our split point
|
# Split the networks apart, using Cell as our split point
|
||||||
# this way we can look at only one network at a time.
|
# this way we can look at only one network at a time.
|
||||||
@@ -1397,7 +1397,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
or not entry['hidden']):
|
or not entry['hidden']):
|
||||||
access_points[entry['bssid']] = entry
|
access_points[entry['bssid']] = entry
|
||||||
|
|
||||||
return access_points.values()
|
return list(access_points.values())
|
||||||
|
|
||||||
def _ParseAccessPoint(self, cell, ralink_info):
|
def _ParseAccessPoint(self, cell, ralink_info):
|
||||||
""" Parse a single cell from the output of iwlist.
|
""" Parse a single cell from the output of iwlist.
|
||||||
@@ -1416,7 +1416,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
try:
|
try:
|
||||||
ap['essid'] = misc.to_unicode(ap['essid'])
|
ap['essid'] = misc.to_unicode(ap['essid'])
|
||||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||||
print 'Unicode problem with current network essid, ignoring!!'
|
print('Unicode problem with current network essid, ignoring!!')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# We (well, DBus) don't support ESSIDs with null bytes in it.
|
# 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', '')
|
ap['essid'] = ap['essid'].replace('\x00', '')
|
||||||
|
|
||||||
if ap['essid'] in ['Hidden', '<hidden>', "", None]:
|
if ap['essid'] in ['Hidden', '<hidden>', "", None]:
|
||||||
print 'hidden'
|
print('hidden')
|
||||||
ap['hidden'] = True
|
ap['hidden'] = True
|
||||||
ap['essid'] = "<hidden>"
|
ap['essid'] = "<hidden>"
|
||||||
else:
|
else:
|
||||||
@@ -1453,7 +1453,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
# Mode
|
# Mode
|
||||||
ap['mode'] = misc.RunRegex(mode_pattern, cell)
|
ap['mode'] = misc.RunRegex(mode_pattern, cell)
|
||||||
if ap['mode'] is None:
|
if ap['mode'] is None:
|
||||||
print 'Invalid network mode string, ignoring!'
|
print('Invalid network mode string, ignoring!')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Break off here if we're using a ralink card
|
# Break off here if we're using a ralink card
|
||||||
@@ -1521,7 +1521,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
output = misc.Run(cmd)
|
output = misc.Run(cmd)
|
||||||
result = misc.RunRegex(auth_pattern, output)
|
result = misc.RunRegex(auth_pattern, output)
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print 'WPA_CLI RESULT IS', result
|
print('WPA_CLI RESULT IS', result)
|
||||||
|
|
||||||
if not result:
|
if not result:
|
||||||
return False
|
return False
|
||||||
@@ -1539,7 +1539,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
disconnected_time = 0
|
disconnected_time = 0
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
print 'wpa_supplicant authentication may have failed.'
|
print('wpa_supplicant authentication may have failed.')
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
@@ -1554,7 +1554,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
time, so we manually speed it up if we see it happening.
|
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'
|
cmd = 'wpa_cli -i' + self.iface + ' scan'
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@@ -1599,7 +1599,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
if not iwlistauth:
|
if not iwlistauth:
|
||||||
cmd = 'iwlist ' + self.iface + ' auth'
|
cmd = 'iwlist ' + self.iface + ' auth'
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
output = misc.Run(cmd)
|
output = misc.Run(cmd)
|
||||||
else:
|
else:
|
||||||
output = iwlistauth
|
output = iwlistauth
|
||||||
@@ -1614,7 +1614,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
|
|
||||||
cmd = 'iwlist ' + self.iface + ' rate'
|
cmd = 'iwlist ' + self.iface + ' rate'
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print cmd
|
print(cmd)
|
||||||
rates = misc.Run(cmd)
|
rates = misc.Run(cmd)
|
||||||
|
|
||||||
# process the output
|
# process the output
|
||||||
|
|||||||
Reference in New Issue
Block a user