replacing bash

This commit is contained in:
age 2006-08-16 07:17:44 +00:00
parent e0ec6cb9a4
commit c473798003
8 changed files with 321 additions and 0 deletions

View file

@ -0,0 +1,94 @@
#!/usr/bin/env python
import re
import CryptoBoxPreferences, CryptoBoxLogger, CryptoBoxContainer
class CryptoBox:
'''Get and set the properties of a CryptoBox'''
def __init__(self):
'''reset all variables to default settings'''
self.cbxPrefs = CryptoBoxPreferences.Preferences()
self.debug = CryptoBoxLogger.CryptoBoxLogger(
self.cbxPrefs["debuglevel"],
self.cbxPrefs["debugfacility"],
self.cbxPrefs["logfile"] )
self.alloweddevices = self.csv2list(self.cbxPrefs["allowed_devices"])
self.containers = []
for device in self.allAvailablePartitions():
if self.deviceIsReallyAllowed(device):
self.containers.append(CryptoBoxContainer.CryptoBoxContainer(device))
############################
### internal methods
def csv2list(self, csvstring):
'''transform a csv preferences string into a list'''
commalist = csvstring.split(",") # split the csv by ","
list = []
for element in commalist:
list.append(element.strip()) # remove whitespaces
return list
def deviceIsReallyAllowed(self, device):
'''return "true" if the given device is white-listed for being used as cryptobox container'''
for a in self.alloweddevices:
if re.search('^' + a, device):
#print "%s allowed for cbx" % a
return True
def allAvailablePartitions(self):
'''retrieve a list of all available containers'''
ret_list = []
try:
fpart = open("/proc/partitions", "r")
try:
line = fpart.readline()
while line:
p_details = line.split()
if (len(p_details) == 4):
(p_major, p_minor, p_size, p_device) = p_details
if re.search('^[0-9]*$', p_major) and re.search('^[0-9]*$', p_minor):
p_parent = re.sub('[1-9]?[0-9]$', '', p_device)
if p_parent == p_device:
if [e for e in ret_list if re.search('^' + p_parent + '[1-9]?[0-9]$', e)]:
"major partition - its children are already in the list"
pass
else:
"major partition - but there are no children for now"
ret_list.append(p_device)
else:
"minor partition - remove parent if necessary"
if p_parent in ret_list: ret_list.remove(p_parent)
ret_list.append(p_device)
line = fpart.readline()
finally:
fpart.close()
return ["/dev/" + e for e in ret_list]
except IOError:
self.debugMessage(
"Could not read /proc/partitions",
CryptoBoxLogger.DebugLevels["warn"])
return []
##################################
### public methods
def debugMessage(self, level, text):
'''print a debug message to the previously choosen debugging facility'''
self.debug.printMessage(level,text)
def getContainerList(self):
'''return a list of all containers of this cryptobox'''
try:
return self.containers[:]
except AttributeError:
return None
def getConfigValue(self, key):
'''return a tuple of key+value from the configfile'''
return (key, self.cbxPrefs[key])
def setConfigValue(self, key, value):
'''save the strings key+value in configfile'''
self.cbxPrefs[key]=value

View file

@ -0,0 +1,6 @@
class CryptoBoxContainer:
def __init__(self, device):
self.device = device

View file

@ -0,0 +1,51 @@
import sys
class CryptoBoxLogger:
DebugLevels = {"debug":0, "info":3, "warn":6, "error":9}
DebugFacilities = {"file":0}
def __init__(self, level, facility, name=None):
self.debug_level = int(level)
if int(facility) == self.DebugFacilities["file"]:
self.logFunc = self.message2file
if name is not None:
self.logFile = name
else:
self.logFile = '/var/log/cryptobox.log'
try:
fsock = open(self.logFile, "a")
fsock.close()
return
except IOError:
sys.stderr.write("Unable to open logfile (%s) for writing.\n" % (self.logFile, ))
else:
sys.stderr.write("Invalid logging facility: %d.\n" % (facility, ))
"we will only arrive here, if an error occoured"
sys.stderr.write("Sorry - bye, bye!\n")
sys.exit(1)
def printMessage(self, text, msg_level=None):
if msg_level is None: msg_level = self.DebugLevels["debug"]
if msg_level >= self.debug_level:
self.logFunc("[CryptoBox] - %s\n" % (text, ))
def message2file(self, text):
try:
log_sock = open(self.logFile, "a")
try:
log_sock.writelines(text)
log_sock.close()
return
except IOError:
sys.stderr.write(
"Unable to write messages to logfile (%s).\n" % (self.logFile, ))
except IOError:
sys.stderr.write("Unable to open logfile (%s) for writing.\n" % (self.logFile, ))
"we will only arrive here, if an error occoured"
sys.stderr.write("Sorry - bye, bye!\n")
sys.exit(1)

View file

@ -0,0 +1,132 @@
#!/usr/bin/env python
"""
This Class is derived mainly from 'gimini' project.
__version__ = "$Revision: 1.1 $"
__author__ = "C.Dutoit <dutoitc@hotmail.com>"
__date__ = "2003-2-14"
Thanx to Dutoit!
"""
from ConfigParser import *
import sys, os
### Set the Preferences filename
PREFS_FILENAME="cbx.conf"
class Preferences:
"""
This class handle preferences and store them into 'PREFS_FILENAME'
To use it :
- instanciate a Preferences object :
myPP=Preferences()
- to get a preference :
mypref=myPP["ma_preference"]
- to set a preference :
myPP["ma_preference"]=xxx
The preferences are automatically loaded on the first instanciation of this
class and are saved when a value is added or changed automatically, too.
"""
def __init__(self):
"""
Constructor
@author C.Dutoit <dutoitc@hotmail.com>
"""
self._config = None
self.__loadConfig()
#>--------------------------------------------------------------------------
def __getitem__(self, name):
"""
Return the preferences for the given item
@param String name : Name of the item for which we return a value
@return String : value of the pref, or None if inexistant
@since 1.1.2.7
@author C.Dutoit <dutoitc@hotmail.com>
"""
if not self._config.has_section("Main"):
print "No section: \"[Main]\""
return None
try:
return self._config.get("Main", name)
except NoOptionError:
print "No such option: \"" + name +"\""
return None
#>--------------------------------------------------------------------------
def __setitem__(self, name, value):
"""
Return the preferences for the given item
@param String name : Name of the item WITHOUT SPACES
@param String Value : Value for the given name
@raises TypeError : if the name contains spaces
@since 1.1.2.7
@author C.Dutoit <dutoitc@hotmail.com>
"""
# Add 'Main' section ?
if not self._config.has_section("Main"):
self._config.add_section("Main")
if " " in list(name):
raise TypeError, "Name cannot contain a space"
# Save
self._config.set("Main", name, str(value))
self.__saveConfig()
#>--------------------------------------------------------------------------
def __saveConfig(self):
"""
Save datas to config file
@since 1.1.2.5
@author C.Dutoit <dutoitc@hotmail.com>
"""
f=open(PREFS_FILENAME, "w")
self._config.write(f)
f.close()
#>--------------------------------------------------------------------------
def __loadConfig(self):
"""
Load datas from config file
@since 1.1.2.5
@author C.Dutoit <dutoitc@hotmail.com>
"""
# Make sure that the configuration file exist
try:
f = open(PREFS_FILENAME, "r")
f.close()
except:
try:
f = open(PREFS_FILENAME, "w")
f.write("")
f.close()
except:
print "Can't make %s for saving preferences !" % PREFS_FILENAME
return
# Read datas
self._config=ConfigParser()
self._config.read(PREFS_FILENAME)
#>--------------------------------------------------------------------------
if __name__ == "__main__":
myPP=Preferences()
mypref=myPP["ma_preference"]
myPP["ma_preference"]="xxx"

View file

View file

@ -0,0 +1,7 @@
[Main]
logfile = cbox.log
allowed_devices = /dev/sda1, /dev/hda1, /dev/hda3, asf
debugfacility = 0
debuglevel = 0
foo = bar

View file

@ -0,0 +1,22 @@
Klassen und Aktionen:
CryptoBox
DebugMessage(level,text)
isDeviceAllowed(devicename)
getConfigValue
setConfigValue
getContainerList(opt: type)
CryptoBoxContainer
getName
getDevice
getUUID
isMounted
getCapacity
mount
umount
create(type, opt: pw...)
getType
CryptoBoxContainerPlain (CryptoBoxContainer)
CryptoBoxContainerLuks (CryptoBoxContainer)
getCipher
changePassword

View file

@ -0,0 +1,9 @@
from CryptoBox import CryptoBox
cb = CryptoBox()
#print "Allowed_Devices: %s" % (cb.getConfigValue("allowed_devices"), )
#print "non-existing: %s" % (cb.getConfigValue("alowed_devices"), )
print [e.device for e in cb.getContainerList()]
print "Config %s" % str(cb.getConfigValue("logfile"))
cb.setConfigValue("foo","bar")