Skip to content

Instantly share code, notes, and snippets.

@zeehio
Last active February 6, 2025 05:11
Show Gist options
  • Save zeehio/36b108b01732699a5efdb10622fcda14 to your computer and use it in GitHub Desktop.
Save zeehio/36b108b01732699a5efdb10622fcda14 to your computer and use it in GitHub Desktop.
Check if subordinate user and group ids exist and suggest how to create them
#!/bin/sh
RED='\033[0;31m'
NOCOLOR='\033[0m' # No Color
GREEN='\033[0;32m'
RANGE_SIZE=65536
USERID="$1"
if [ "${USERID}" = "" ]; then
echo "ERROR: You must specify a user name as first argument"
exit 1
fi
if getent passwd "${USERID}" ; then
echo -e "${GREEN}INFO: User ${USERID} is valid${NOCOLOR}"
else
echo -e "${RED}ERROR: Invalid user name ${USERID}${NOCOLOR}"
exit 1
fi
echo "INFO: Checking subordinate user ids for user: $USERID"
SUBUID_FOUND=0
if grep "${USERID}:" /etc/subuid ; then
echo "INFO: Subordinate user ids found for $USERID."
SUBUID_FOUND=1
else
echo "INFO: Subordinate user ids NOT found for $USERID."
fi
echo "INFO: Checking subordinate group ids for user: $USERID"
SUBGID_FOUND=0
if grep "${USERID}:" /etc/subgid ; then
echo "INFO: Subordinate group ids found for $USERID."
SUBGID_FOUND=1
else
echo "INFO: Subordinate group ids NOT found for $USERID."
fi
if [ "${SUBUID_FOUND}" = "1" -a "${SUBGID_FOUND}" = "1" ]; then
echo -e "${GREEN}INFO: Both user and group subordinate ids were found. All is good. Exiting${NOCOLOR}"
exit 0
fi
if [ "${SUBUID_FOUND}" = "0" ]; then
echo "INFO: Subordinate USER ids not found for $USERID. Creating them..."
LAST_SUBUID=$(cut -d: -f2 /etc/subuid | sort -n | tail -1)
if [[ -z $LAST_SUBUID ]]; then
NEXT_SUBUID=1000000
else
NEXT_SUBUID=$(( $LAST_SUBUID + $RANGE_SIZE ))
fi
SUBUID_START="${NEXT_SUBUID}"
SUBUID_LAST=$(( $SUBUID_START + $RANGE_SIZE - 1 ))
echo "INFO: Please add subordinate USER id range to user running the command:"
echo -e "${RED}sudo usermod --add-subuids ${SUBUID_START}-${SUBUID_LAST} ${USERID}${NOCOLOR}"
fi
if [ "${SUBGID_FOUND}" = "0" ]; then
echo "INFO: Subordinate GROUP ids not found for $USERID. Creating them..."
LAST_SUBGID=$(cut -d: -f2 /etc/subgid | sort -n | tail -1)
if [[ -z $LAST_SUBGID ]]; then
NEXT_SUBGID=1000000
else
NEXT_SUBGID=$(( $LAST_SUBGID + $RANGE_SIZE ))
fi
SUBGID_START="${NEXT_SUBGID}"
SUBGID_LAST=$(( $SUBGID_START + $RANGE_SIZE - 1 ))
echo "INFO: Adding subordinate GROUP id range to user running the command:"
echo -e "${RED}sudo usermod --add-subgids ${SUBGID_START}-${SUBGID_LAST} ${USERID}${NOCOLOR}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment