
258
|
Appendix: bash Script Samples
# Check whether the user already exists.
# If so, report this and skip this user.
result=$( egrep "^$username:" < /etc/passwd )
if [[ -n "$result" ]] ; then
echo "User '$username' already exists"
continue
fi
# Check whether the group already exists.
# If not, add the group.
result=$( egrep "^$groupname:" < /etc/group )
if [[ -z "$result" ]] ; then
groupadd "$groupname"
fi
# Add the user.
useradd -c "$realname" \
-d "/home/$username" \
-e "$expiredate" \
-f 365 \
-g "$groupname" \
-m \
-s /bin/bash \
"$username"
if [[ $? == 0 ]]; then
echo "Successfully added user '$username'."
else
echo "Error adding user '$username' (group \
'$groupname', real name '$realname')"
exit 1
fi
done
Random Password Generator
Here’s a script that generates a password of any requested length, in ASCII characters:
#!/bin/bash
n="$1"
[[ -n "$n" ]] || n=12
if [[ $n -lt 8 ]]; then
echo "A password of length $n would be too weak"
exit 1
fi
p=$( dd if=/dev/urandom bs=512 count=1 2>/dev/null \
| tr -cd 'a-zA-Z0-9' \
| cut -c 1-$n )
echo "${p}"