Skip to content

Instantly share code, notes, and snippets.

@dougwollison
Created March 19, 2015 18:14
Show Gist options
  • Save dougwollison/d1c58459e956cc631066 to your computer and use it in GitHub Desktop.
Save dougwollison/d1c58459e956cc631066 to your computer and use it in GitHub Desktop.
Kick user from server (kills all SSH sessions for them)
#!/bin/bash
# Make sure at least the first parameter is set
if [ -z "$1" ]; then
echo "Usage: kick [-d] user"
exit
fi
# Check if the -d flag (delete) is set
if [[ "$1" == '-d' ]]; then
user=$2
del='yes'
elif [[ "$2" == '-d' ]]; then
user=$1
del='yes'
else
user=$1
del='no'
fi
# Get the original starter of the script
starter=$(who am i | awk '{print $1}')
# Abort if the starter is trying to kick themselves
if [[ "$starter" == "$user" ]]; then
echo "Umm... no; I'm not kicking you."
exit
fi
# Get the list of process ids and users for each ssh process
pids=$(ps ax| grep sshd | grep "@pts/" | awk '{ print $1 }')
users=$(ps ax| grep sshd | grep "@pts/" | awk '{ print $6 }' | sed -r "s/@pts\/[0-9]?//")
# Split into arrays
pids=(${pids// /})
users=(${users// /})
# Loop through each user
for u in "${!users[@]}"
do
# If they're the right user, kill the ssh process
if [[ "${users[u]}" == $user ]]; then
echo "Kicking $user (pid ${pids[u]})"
kill -9 "${pids[u]}"
fi
done
# Once done, delete the user if desired
if [[ "$del" == 'yes' ]]; then
userdel "$user"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment