Here code from a script to unlock a LUKS device before making a backup to the device. I use LUKS for encrypting hard drives for off-site storage.
print ("Determine if luks device mapper link exists. If link exists, then luks is open")
answer = os.path.islink(luks_location)
print ("Result of luks device being open: ", answer)
if answer == False:
#luks device is closed, attempt to open
print ("Attempting to open luks device: ", luks_device_uuid)
subprocess.call("cryptsetup luksOpen " + "--key-file " + repr(luks_keyfile) + " " + repr(luks_device_uuid) + " " + repr(luks_name), shell=True)
answer = os.path.islink(luks_location)
# test to see if luksOpen failed and need to exit program
if answer == False:
# luksopen failed, exit program
print ("luks device failed to open. The answer variable is: ", answer)
sys.exit ("Exiting program now.")
else:
# luksopen was successful
print ("luks device is now open: ", answer)
print ("luks location is: ", luks_location)
print ("luks device mapper name is: ", luks_name)
else:
# luks device was already open
print ("luks device is already open: ", answer)
print ("luks location is: ", luks_location)
print ("luks device mapper name is: ", luks_name)
sys.exit("exiting program")
Next blog will be mounting the device with python.