diff --git a/README.rst b/README.rst index 1df343a..476161b 100644 --- a/README.rst +++ b/README.rst @@ -46,6 +46,16 @@ To update the on-disk filesystem table, call ``save()``:: fs.options.add('user_xattr') fstab.save() +You can get UUID of drive by using ``get_uuid()`` method, like this:: + + with FilesystemTable() as fstab: + for fs in fstab: + print "%s = %s" % (fs.source, fs.get_uuid()) + +Getting proper results from get_uuid() requires root access on some systems. If drive does +not have UUID, or you don't have permissions to read it, get_uuid() will return empty string. +UUID detection requires libblkid installed in your system. + Limitations ----------- diff --git a/libmount/fstab.py b/libmount/fstab.py index f4fb186..eef3197 100644 --- a/libmount/fstab.py +++ b/libmount/fstab.py @@ -14,6 +14,18 @@ else: raise ImportError("Could not find libmount shared object. Is libmount installed?") + +libnames = ('libblkid.so', 'libblkid.so.1') +for libname in libnames: + try: + _libblkid = ctypes.cdll.LoadLibrary(libname) + except OSError: + continue + break +else: + _libblkid = False + + class FilesystemTable(list): class Options(set): """A sub-type of set for maintaining filesystem options.""" @@ -90,6 +102,24 @@ def _set_options(self, value): del self._options options = property(_get_options, _set_options) + + def get_uuid(self): + """ Returns UUID of self.source drive + requires root permissions + """ + if not _libblkid or not self.source: + return '' + if self.source[0:5].lower() == 'uuid=': + return self.source[5:].lower() + pr = _libblkid.blkid_new_probe_from_filename( self.source ) + if pr == 0: + return '' + uuid = ctypes.c_char_p('') + _libblkid.blkid_do_probe(pr); + _libblkid.blkid_probe_lookup_value(pr, 'UUID', ctypes.byref(uuid), None); + _libblkid.blkid_free_probe(pr); + return uuid.value.lower() + def __unicode__(self): return "%s on %s type %s (%s)" % (self.source, self.target, @@ -173,4 +203,4 @@ def save(self): def get_fstab_readonly(): return FilesystemTable('/etc/fstab', readonly=True) def get_current_mounts(): - return FilesystemTable('/proc/mounts', readonly=True) \ No newline at end of file + return FilesystemTable('/proc/mounts', readonly=True)