Skip to content

Instantly share code, notes, and snippets.

@chendo
Created January 21, 2010 06:03
Show Gist options
  • Save chendo/282619 to your computer and use it in GitHub Desktop.
Save chendo/282619 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Disclaimer: my first bash script
# User purger - removes the user and their public keys from a system
# By chendo
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
read -p "Enter username to be deleted (or leave blank to delete key): " target_user
if [ "$target_user" == "" ]; then
read -p "Enter part of public key (must be more than 10 characters): " key
if [ test $(expr length "$key") -lt 10 ]; then
echo "Less than 10 characters, bailing"
exit 1
fi
output=$(
for f in `cut -d : -f 6 /etc/passwd`; do
grep -nHs "$key" $f/.ssh/authorized_keys
done
)
else
home_folder=( $(grep $target_user /etc/passwd | cut -d : -f 6))
keys="$home_folder/.ssh/authorized_keys"
output=$(while read key; do
if [[ $key =~ ^.{,10}$ ]]; then
continue
fi
for f in `cut -d : -f 6 /etc/passwd`; do
grep -nHs "$key" $f/.ssh/authorized_keys
done
done < "$keys" )
fi
while read line; do
filename=$(echo "$line" | cut -d : -f 1)
line_no=$(echo "$line" | cut -d : -f 2)
if [ $filename ]; then
echo "$line"
fi
done < <(echo "$output")
read -p "Are you sure you want to delete these instances of the public keys? (yes/no) " confirm
if [ "$confirm" == "yes" ]; then
while read line; do
filename=$(echo "$line" | cut -d : -f 1)
line_no=$(echo "$line" | cut -d : -f 2)
if [ $filename ]; then
sed -i ${line_no}d "$filename"
fi
done < <(echo "$output")
fi
if [[ $target_user =~ ^.+$ ]]; then
read -p "Are you sure you want to delete the user? (yes/no) " confirm
if [ "$confirm" == "yes" ]; then
deluser $target_user
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment