Skip to content

Instantly share code, notes, and snippets.

@niedbalski
Created May 22, 2014 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save niedbalski/7ad27596c8713d931ede to your computer and use it in GitHub Desktop.
Save niedbalski/7ad27596c8713d931ede to your computer and use it in GitHub Desktop.
python-fstab.py
class Fstab(file):
class Entry(object):
def __init__(self, device, mountpoint, filesystem,
options, d=0, p=0):
self.device = device
self.mountpoint = mountpoint
self.filesystem = filesystem
if not options:
options = "defaults"
self.options = options
self.d = d
self.p = p
def __str__(self):
return "{} {} {} {} {} {}".format(self.device,
self.mountpoint,
self.filesystem,
self.options,
self.d,
self.p)
_path = os.path.join(os.path.sep, 'etc', 'fstab')
def __init__(self):
file.__init__(self, self._path, 'r+')
@property
def entries(self):
for line in self.readlines():
if not line.startswith("#"):
try:
(dev, mp, fs, options, d, p) = line.split(" ")
yield Fstab.Entry(dev, mp, fs, options, d=d, p=p)
except ValueError:
pass
def get_entry_by_attr(self, attr, value):
for entry in self.entries:
e_attr = getattr(entry, attr)
if e_attr == value:
return entry
return None
def add_entry(self, entry):
if not self.get_entry_by_attr('device', entry.device):
return self.write(str(entry))
return False
def delete_entry(self, entry):
self.seek(0)
lines = self.readlines()
for index, line in enumerate(lines):
if line == str(entry):
lines.remove(line)
self.seek(0)
self.write(''.join(lines))
self.truncate()
return True
@classmethod
def remove_by_mountpoint(cls, mountpoint):
fstab = cls()
entry = fstab.get_entry_by_attr('mountpoint', mountpoint)
if entry:
return fstab.delete_entry(entry)
return False
@classmethod
def add(cls, device, mountpoint, filesystem, options=None):
return cls().add_entry(Fstab.Entry(device, mountpoint, filesystem,
options=options))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment