Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@targzeta
Created October 15, 2019 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save targzeta/e8fd1da285510054ba17e05adac81c50 to your computer and use it in GitHub Desktop.
Save targzeta/e8fd1da285510054ba17e05adac81c50 to your computer and use it in GitHub Desktop.
Mounting LUKS filesystem like usual
#!/bin/bash
#
# Copyright (C) 2019 Emanuele Tomasi <targzeta@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Mounting LUKS filesystem like usual.
# Running without arguments for the help.
function _exit {
if type "$1" >& /dev/null
then
$1
else
echo "$1"
fi
(( $2 == 2 )) && echo && _usage
exit $2
}
function _usage {
cat <<- EOL
Usage: $SCRIPT_NAME device|dir
or: $SCRIPT_NAME device dir
or: $SCRIPT_NAME -u dir|device
EOL
}
SCRIPT_NAME=${0##*/u}
############################
# PARSING THE COMMAND LINE #
############################
[[ $# < 1 || $# > 2 ]] && _exit _usage 1
UMOUNT=0
while getopts :u arg
do
case $arg in
u) UMOUNT=1
esac
done
shift $(( $OPTIND-1 ))
[[ ${0##*/} =~ ^umount ]] && UMOUNT=1
#################
# SANITY CHECKS #
#################
[[ $(whoami) != 'root' ]] &&
_exit 'Only root can do it!' 1
declare -a dev_dir
if (( $UMOUNT == 1 ))
then
(( $# != 1 )) && _exit _usage 1
dev_dir=($(grep "\s${1%/}\s" /etc/mtab | awk '{print $1 " " $2}'))
else
if (( $# == 1 ))
then
dev_dir=($(grep "\s${1%/}\s" /etc/fstab | awk '{print $1 " " $2}'))
else
dev_dir=("$1" "$2")
fi
fi
[ -z "${dev_dir[0]}" ] && _exit "Dir or device not found: $1" 2
[ ! -b "${dev_dir[0]}" ] && _exit "Device not found: ${dev_dir[0]}" 2
[ ! -d "${dev_dir[1]}" ] && _exit "Dir not found: ${dev_dir[1]}" 2
########
# MAIN #
########
DM_NAME=$(basename "${dev_dir[1]}")
if (( $UMOUNT == 0 ))
then
cryptsetup open --type luks "${dev_dir[0]}" "$DM_NAME"
ret_code=$?
(( $ret_code == 2 )) && _exit "Wrong password?" 1
(( $ret_code != 0 )) && exit 1
mount /dev/mapper/"$DM_NAME" "${dev_dir[1]}"
else
umount "${dev_dir[1]}" && cryptsetup close $DM_NAME
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment