Files
passwd-to-ldap/passwd-to-ldap-chpass
2025-03-03 08:53:58 +08:00

41 lines
1.2 KiB
Bash
Executable File

#!/bin/bash
# get the script dirname
BINPATH="$(readlink "$0" || echo "$0")"
DIRPATH="$(dirname "$BINPATH")"
if ! [ -r "$DIRPATH/config" ]; then echo "Unable to read config file"; exit 128; fi
source "$DIRPATH/config"
# run as root
if [ "$EUID" -ne 0 ]; then echo "Must be run as root"; exit 64; fi
# Get user details
USERNAME=$1
if [ -z "$USERNAME" ]; then echo "No username supplied"; exit 1; fi
PASSDB="$(getent passwd $USERNAME)"
if [ -z "$PASSDB" ]; then echo "User $USERNAME not found"; exit 2; fi
UIDNUMBER="$(echo $PASSDB | cut -f 3 -d :)"
# enforce uid limits
UIDNUMBER_MIN=1000
UIDNUMBER_MAX=10000
if [ "$UIDNUMBER" -lt "$UIDNUMBER_MIN" ]; then echo "Refusing to update user below $UIDNUMBER_MIN"; exit 4; fi
if [ "$UIDNUMBER" -gt "$UIDNUMBER_MAX" ]; then echo "Refusing to update user above $UIDNUMBER_MAX"; exit 4; fi
# Get encrypted password hash
SHADOWDB="$(getent shadow "$USERNAME")"
if [ -z "$SHADOWDB" ]; then echo "$USERNAME password not found"; exit 8; fi
SECRET="$(echo "$SHADOWDB" | cut -f 2 -d :)"
ldapmodify -D "$BIND" -w "$PASS" -H ldapi:/// <<-LDIF
dn: cn=$USERNAME,$USER_BASEDN
changeType: modify
replace: userPassword
userPassword: {CRYPT}$SECRET
LDIF