Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that an encrypted disk was previously open using cryptsetup?

I am writing a shell script (meant to work with Ubuntu only) that assumes that a disk has been previously open (using the command below) to make operations on it (resize2fs, lvcreate, ...). However, this might not always be the case, and when the disk is closed, the user of the script has to run this line before running the script, asking for his/her passphrase:

sudo cryptsetup luksOpen /dev/sdaX sdaX_crypt

Ideally, the script should start with this command, simplifying the user sequence. However, if the disk was indeed already opened, the script will fail because an encrypted disk cannot be opened twice.

How can I check if the disk was previously open? Is checking that /dev/mapper/sdX_crypt exists a valid solution / enough? If not or not possible, is there a way to make the command run only if necessary?

like image 954
astorije Avatar asked Oct 25 '25 12:10

astorije


1 Answers

You can use the lsblk command.

If the disk is already unlocked, it will display two lines: the device and the mapped device, where the mapped device should be of type crypt.

# lsblk -l -n /dev/sdaX
sdaX   253:11   0   2G  0  part
sdaX_crypt (dm-6) 253:11   0   2G  0  crypt

If the disk is not yet unlocked, it will only show the device.

# lsblk -l -n /dev/sdaX
sdaX   253:11   0   2G  0  part
like image 79
alvinabad Avatar answered Oct 28 '25 04:10

alvinabad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!