自动挂载加密文件

之前说到使用cryptsetup加密虚拟磁盘文件, 加密完成后想要打开加密文件每次都要输入那么多条命令很麻烦,想到能不能写一个shell脚本来简化使用过程,于是这个脚本就这样来的.

挂载

mount_encrypted_virtual_disk.sh脚本的作用是挂载已经加密好的虚拟磁盘文件(encrypted.vol)到指定目录

#!/bin/bash

if [ `id -u` -ne 0 ];then
echo "non-root user"
exit
fi

if [ -z $1 -o -z $2 ];then
program=`basename $0`
echo -e "$program\tfilename\tmount_dir"
exit
fi

filename=$1
mount_dir=$2
mapper_dir=/dev/mapper

mounted_success_flag="$mapper_dir"/`basename $filename`
already_mount=`df -h | grep $mounted_success_flag | wc -l`
if [ $already_mount -eq 1 ];then
echo "$mounted_success_flag already mounted"
exit
fi

count=`ls $mount_dir | wc -l`
if [ $count -gt 0 ];then
echo "$mount_dir is not a empty directory"
exit
fi

device="`basename ${filename}`"
sudo cryptsetup luksOpen $filename $device
if [ ! -L $mapper_dir/$device ];then
echo "$mapper_dir/$device is not exist"
exit
fi

if [ ! -d $mount_dir ];then
mkdir -p $mount_dir
fi
mount $mapper_dir/$device $mount_dir

使用举例, 把encrypted.vol解密并且挂载到/mnt目录

sudo ./mount_encrypted_virtual_disk.sh encrypted.vol /mnt

卸载

关机或者重启是可以自动卸载已经挂载的设备,我们也可以手动卸载,umount_encrypted_virtual_disk.sh脚本会卸载所有已经挂载的加密后的虚拟磁盘文件.

#!/bin/bash

if [ `id -u` -ne 0 ];then
echo "non-root user"
exit
fi

mapper_dir=/dev/mapper
count=`df -h | grep "$mapper_dir" | wc -l`

for((index=0; index<$count; index++))
do
string=`df -h | grep "$mapper_dir" | awk '{print $1"#"$6}'`
string=${string//#/ };
array=($string)

device=${array[0]}
mounted_dir=${array[1]}
umount $mounted_dir && cryptsetup close $device
done

使用举例, 卸载所有已挂载加密磁盘.

sudo ./umount_encrypted_virtual_disk.sh