Last active
January 30, 2017 19:37
-
-
Save cholcombe973/347f5ec76da03c94fabad776733a0223 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from _ctypes import POINTER, byref | |
import ctypes | |
import os | |
def get_block_uuid(block_dev): | |
""" | |
This queries blkid to get the uuid for a block device. | |
:param block_dev: Name of the block device to query. | |
:return: The UUID of the device or None on Error. | |
""" | |
try: | |
blkid = ctypes.cdll.LoadLibrary("libblkid.so") | |
# extern int blkid_probe_lookup_value(blkid_probe pr, const char *name, | |
# const char **data, size_t *len); | |
blkid.blkid_new_probe_from_filename.argtypes = [ctypes.c_char_p] | |
blkid.blkid_probe_lookup_value.argtypes = [ctypes.c_void_p, | |
ctypes.c_char_p, | |
POINTER(ctypes.c_char_p), | |
POINTER(ctypes.c_ulong)] | |
except OSError as err: | |
print('get_block_uuid loading libblkid.so failed with error: {}'.format(os.strerror(err.errno))) | |
raise err | |
if not os.path.exists(block_dev): | |
return None | |
probe = blkid.blkid_new_probe_from_filename(ctypes.c_char_p(block_dev)) | |
blkid.blkid_do_probe(probe) | |
if probe < 0: | |
print('get_block_uuid new_probe_from_filename failed: {}'.format(os.strerror(probe))) | |
raise OSError(probe, os.strerror(probe)) | |
result = blkid.blkid_do_safeprobe(probe) | |
print("do_probe: {}".format(result)) | |
if result != 0: | |
print('get_block_uuid do_probe failed with error: {}'.format(os.strerror(result))) | |
raise OSError(result, os.strerror(result)) | |
uuid = ctypes.c_char_p() | |
result = blkid.blkid_probe_lookup_value(probe, | |
ctypes.c_char_p('UUID'.encode('ascii')), | |
byref(uuid), None) | |
if result < 0: | |
print('get_block_uuid lookup_value failed with error: {}'.format(os.strerror(result))) | |
raise OSError(probe, os.strerror(probe)) | |
blkid.blkid_free_probe(probe) | |
return ctypes.string_at(uuid).decode('ascii') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment