Browse Source

Convert to Python 3

master
Pekka Helenius 4 years ago
parent
commit
3d41162fa8
2 changed files with 40 additions and 48 deletions
  1. +8
    -16
      tools/pamusb-agent
  2. +32
    -32
      tools/pamusb-conf

+ 8
- 16
tools/pamusb-agent View File

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python
# #
# Copyright (c) 2003-2007 Andrea Luzzardi <scox@sig11.org> # Copyright (c) 2003-2007 Andrea Luzzardi <scox@sig11.org>
# #
@ -12,7 +12,7 @@
# details. # details.
# #
# You should have received a copy of the GNU General Public License along with # You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301 USA. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os import os
@ -27,15 +27,7 @@ gi.require_version('UDisks', '2.0')
from gi.repository import GLib from gi.repository import GLib
from gi.repository import UDisks from gi.repository import UDisks
try:
# Python 2.5
import xml.etree.ElementTree as et
except ImportError:
# Python 2.4
try:
import cElementTree as et
except ImportError:
import elementtree.ElementTree as et
import xml.etree.ElementTree as et
class HotPlugDevice: class HotPlugDevice:
def __init__(self, serial): def __init__(self, serial):
@ -49,7 +41,7 @@ class HotPlugDevice:
self.__registerSignals() self.__registerSignals()
self.__running = True self.__running = True
GLib.MainLoop().run() GLib.MainLoop().run()
print 'signals registered'
print('signals registered')
def addCallback(self, callback): def addCallback(self, callback):
self.__callbacks.append(callback) self.__callbacks.append(callback)
@ -111,8 +103,8 @@ class Log:
syslog.syslog(priority, message) syslog.syslog(priority, message)
def usage(): def usage():
print 'Usage: %s [--help] [--config=path] [--daemon] [--check=path]' % \
os.path.basename(__file__)
print('Usage: %s [--help] [--config=path] [--daemon] [--check=path]' % \
os.path.basename(__file__))
sys.exit(1) sys.exit(1)
import getopt import getopt
@ -142,8 +134,8 @@ for o, a in opts:
if not os.path.exists(options['check']): if not os.path.exists(options['check']):
print '%s not found.' % options['check']
print "You might specify manually pamusb-check's location using --check."
print('%s not found.' % options['check'])
print("You might specify manually pamusb-check's location using --check.")
usage() usage()
username = pwd.getpwuid(os.getuid())[0] username = pwd.getpwuid(os.getuid())[0]


+ 32
- 32
tools/pamusb-conf View File

@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python
# #
# Copyright (c) 2003-2007 Andrea Luzzardi <scox@sig11.org> # Copyright (c) 2003-2007 Andrea Luzzardi <scox@sig11.org>
# #
@ -12,7 +12,7 @@
# details. # details.
# #
# You should have received a copy of the GNU General Public License along with # You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301 USA. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
import sys import sys
@ -32,12 +32,12 @@ class Device:
if not driveObj.get_property('removable'): if not driveObj.get_property('removable'):
# Workaround for removable devices with fixed media (such as SD cards) # Workaround for removable devices with fixed media (such as SD cards)
if not "mmcblk" in udi: if not "mmcblk" in udi:
raise Exception, 'Not a removable device'
raise Exception('Not a removable device')
self.vendor = driveObj.get_property('vendor') self.vendor = driveObj.get_property('vendor')
self.product = driveObj.get_property('model') self.product = driveObj.get_property('model')
self.serialNumber = driveObj.get_property('serial') self.serialNumber = driveObj.get_property('serial')
if len(self.volumes()) < 1: if len(self.volumes()) < 1:
raise Exception, 'Device does not contain any volume'
raise Exception('Device does not contain any volume')
def volumes(self): def volumes(self):
vols = [] vols = []
@ -59,17 +59,17 @@ class Device:
def listOptions(question, options, autodetect = True): def listOptions(question, options, autodetect = True):
if autodetect == True and len(options) == 1: if autodetect == True and len(options) == 1:
print question
print "* Using \"%s\" (only option)" % options[0]
print
print(question)
print("* Using \"%s\" (only option)" % options[0])
print()
return 0 return 0
while True: while True:
try: try:
print question
print(question)
for i in range(len(options)): for i in range(len(options)):
print "%d) %s" % (i, options[i])
print
print( "%d) %s" % (i, options[i]))
print()
sys.stdout.write('[%s-%s]: ' % (0, len(options) - 1)) sys.stdout.write('[%s-%s]: ' % (0, len(options) - 1))
optionId = int(sys.stdin.readline()) optionId = int(sys.stdin.readline())
print print
@ -85,16 +85,16 @@ def writeConf(options, doc):
f = open(options['configFile'], 'w') f = open(options['configFile'], 'w')
doc.writexml(f) doc.writexml(f)
f.close() f.close()
except Exception, err:
print 'Unable to save %s: %s' % (options['configFile'], err)
except Exception as err:
print('Unable to save %s: %s' % (options['configFile'], err))
sys.exit(1) sys.exit(1)
else: else:
print 'Done.'
print('Done.')
def shouldSave(options, items): def shouldSave(options, items):
print "\n".join(["%s\t\t: %s" % item for item in items])
print
print 'Save to %s ?' % options['configFile']
print("\n".join(["%s\t\t: %s" % item for item in items]))
print()
print('Save to %s ?' % options['configFile'])
sys.stdout.write('[Y/n] ') sys.stdout.write('[Y/n] ')
response = sys.stdin.readline().strip() response = sys.stdin.readline().strip()
if len(response) > 0 and response.lower() != 'y': if len(response) > 0 and response.lower() != 'y':
@ -107,17 +107,17 @@ def prettifyElement(element):
def addUser(options): def addUser(options):
try: try:
doc = minidom.parse(options['configFile']) doc = minidom.parse(options['configFile'])
except Exception, err:
print 'Unable to read %s: %s' % (options['configFile'], err)
except Exception as err:
print('Unable to read %s: %s' % (options['configFile'], err))
sys.exit(1) sys.exit(1)
devSection = doc.getElementsByTagName('devices') devSection = doc.getElementsByTagName('devices')
if len(devSection) == 0: if len(devSection) == 0:
print 'Malformed configuration file: No <devices> section found.'
print('Malformed configuration file: No <devices> section found.')
sys.exit(1) sys.exit(1)
devicesObj = devSection[0].getElementsByTagName('device') devicesObj = devSection[0].getElementsByTagName('device')
if len(devicesObj) == 0: if len(devicesObj) == 0:
print 'No devices found.'
print 'You must add a device (--add-device) before adding users'
print('No devices found.')
print('You must add a device (--add-device) before adding users')
sys.exit(1) sys.exit(1)
devices = [] devices = []
@ -147,18 +147,18 @@ def addDevice(options):
for udi in [o.get_object_path() for o in udisksObjectManager.get_objects() if o.get_drive()]: for udi in [o.get_object_path() for o in udisksObjectManager.get_objects() if o.get_drive()]:
try: try:
if options['verbose']: if options['verbose']:
print 'Inspecting %s' % udi
print('Inspecting %s' % udi)
devices.append(Device(udi)) devices.append(Device(udi))
except Exception, ex:
except Exception as ex:
if options['verbose']: if options['verbose']:
print "\tInvalid: %s" % ex
print("\tInvalid: %s" % ex)
pass pass
else: else:
if options['verbose']: if options['verbose']:
print "\tValid"
print("\tValid")
if len(devices) == 0: if len(devices) == 0:
print 'No devices detected. Try running in verbose (-v) mode to see what\'s going on.'
print('No devices detected. Try running in verbose (-v) mode to see what\'s going on.')
sys.exit() sys.exit()
device = devices[listOptions("Please select the device you wish to add.", devices)] device = devices[listOptions("Please select the device you wish to add.", devices)]
@ -171,7 +171,7 @@ def addDevice(options):
)] )]
if volume['uuid'] == '': if volume['uuid'] == '':
print 'WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device']
print('WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device'])
shouldSave(options,[ shouldSave(options,[
('Name', options['deviceName']), ('Name', options['deviceName']),
@ -183,8 +183,8 @@ def addDevice(options):
try: try:
doc = minidom.parse(options['configFile']) doc = minidom.parse(options['configFile'])
except Exception, err:
print 'Unable to read %s: %s' % (options['configFile'], err)
except Exception as err:
print('Unable to read %s: %s' % (options['configFile'], err))
sys.exit(1) sys.exit(1)
devs = doc.getElementsByTagName('devices') devs = doc.getElementsByTagName('devices')
@ -195,7 +195,7 @@ def addDevice(options):
if device.getAttribute("id") == options['deviceName']: if device.getAttribute("id") == options['deviceName']:
msg = [ '\nWARNING: A device node already exits for new device \'%s\'.', msg = [ '\nWARNING: A device node already exits for new device \'%s\'.',
'\nTo proceed re-run --add-device using a different name or remove the existing entry in %s.' ] '\nTo proceed re-run --add-device using a different name or remove the existing entry in %s.' ]
print '\n'.join(msg) % (options['deviceName'], options['configFile'])
print('\n'.join(msg) % (options['deviceName'], options['configFile']))
sys.exit(2) sys.exit(2)
dev = doc.createElement('device') dev = doc.createElement('device')
@ -223,7 +223,7 @@ def addDevice(options):
writeConf(options, doc) writeConf(options, doc)
def usage(): def usage():
print 'Usage: %s [--help] [--verbose] [--config=path] [--add-user=name | --add-device=name]' % os.path.basename(__file__)
print('Usage: %s [--help] [--verbose] [--config=path] [--add-user=name | --add-device=name]' % os.path.basename(__file__))
sys.exit(1) sys.exit(1)
import getopt import getopt
@ -253,7 +253,7 @@ for o, a in opts:
options['configFile'] = a options['configFile'] = a
if options['deviceName'] is not None and options['userName'] is not None: if options['deviceName'] is not None and options['userName'] is not None:
print 'You cannot use both --add-user and --add-device'
print('You cannot use both --add-user and --add-device')
usage() usage()
if options['deviceName'] is None and options['userName'] is None: if options['deviceName'] is None and options['userName'] is None:


Loading…
Cancel
Save