Skip to content

Commit f8bd113

Browse files
committed
script updated
1 parent 2b256d0 commit f8bd113

File tree

1 file changed

+87
-8
lines changed

1 file changed

+87
-8
lines changed

del_account.sh

Lines changed: 87 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,100 @@
11
#!/bin/bash
22

3-
# This script deletes a user
3+
# This script deletes, disables or archives users
4+
5+
readonly ARCHIVE_DIR='/archive'
6+
usage() {
7+
echo "Usage: ${0} [-dra] USER [USERN]..." >&2
8+
echo 'Disable a local Linux account.' >&2
9+
echo '-d Deletes accounts.' >&2
10+
echo '-r Romves the home dir associated w/ the accounts.' >&2
11+
echo '-a Creates an archive of the home directory associated with accounts.' >&2
12+
13+
exit 1
14+
}
15+
416
# run as root
517
if [[ "${UID}" -ne 0 ]]
618
then
719
echo 'Please run with sudo or as root!' >&2
820
exit 1
921
fi
1022

11-
USER="$1"
12-
userdel ${USER}
23+
while getopts dra OPTION
24+
do
25+
case ${OPTION} in
26+
d) DELETE_USER='true';;
27+
r) REMOVE_OPTION='-r';;
28+
a) ARCHIVE='true';;
29+
?) usage ;;
30+
esac
31+
done
1332

14-
if [[ "${?}" -ne 0 ]]
15-
then
16-
echo "The account ${USER} was already deleted." >&2
17-
exit 1
33+
if [[ "${#}" -lt 1 ]]
34+
then
35+
usage
1836
fi
1937

20-
echo "The account ${USER} was deleted."
38+
for USERNAME in "${@}"
39+
do
40+
echo "Processing user: ${USERNAME}"
41+
42+
USERID=$(id -u ${USERNAME})
43+
if [[ "${USERID}" -lt 1000 ]]
44+
then
45+
echo "Refusing to remove the ${USERNAME}" >&2
46+
exit 1
47+
fi
48+
49+
if [[ "${ARCHIVE}" = 'true' ]]
50+
then
51+
if [[ ! -d "${ARCHIVE_DIR}" ]]
52+
then
53+
echo "Creating ${ARCHIVE_DIR} directory."
54+
mkdir -p ${ARCHIVE_DIR}
55+
if [[ "${?}" -ne 0 ]]
56+
then
57+
echo "The archive directory could not be created." >&2
58+
exit 1
59+
fi
60+
fi
61+
62+
HOME_DIR="/home/${USERNAME}"
63+
ARCHIVE_FILE="${ARCHIVE_DIR}/${USERNAME}.tgz"
64+
if [[ -d "${HOME_DIR}" ]]
65+
then
66+
echo "Archiving ${HOME_DIR} to ${ARCHIVE_FILE}"
67+
tar -zcf ${ARCHIVE_FILE} ${HOME_DIR} &> /dev/null
68+
if [[ "${?}" -ne 0 ]]
69+
then
70+
echo "Cannot create ${ARCHIVE_FILE}" >&2
71+
exit 1
72+
fi
73+
else
74+
echo "${HOME_DIR} does not exist or is not a dir..." >&2
75+
exit 1
76+
fi
77+
fi
78+
79+
if [[ "${DELETE_USER}" = 'true' ]]
80+
then
81+
# Delete a user
82+
userdel ${REMOVE_OPTION} ${USERNAME}
83+
# CHECK if it was successful
84+
if [[ "${?}" -ne 0 ]]
85+
then
86+
echo "The account ${USERNAME} was not deleted" >&2
87+
exit 1
88+
fi
89+
echo "The accout ${USERNAME} was deleted."
90+
else
91+
chage -E 0 ${USERNAME}
92+
if [[ "${?}" -ne 0 ]]
93+
then
94+
echo "The account ${USERNAME} was already deleted." >&2
95+
exit 1
96+
fi
97+
echo "The account ${USERNAME} was disabled."
98+
fi
99+
done
21100
exit 0

0 commit comments

Comments
 (0)