Problem overview.
The challenge this resource is designed to solve.
Whether a Linux device is compromised, lost, or subject to strict compliance standards, instantly revoking user access is paramount. This script securely locks all local and SSH-enabled accounts, ensuring no one can log in or remain logged in, all without losing remote management capabilities through Level.
About this resource.
What it does and how it fits into your workflow.
This script finds all currently logged-in users and terminates their sessions, effectively booting them off the system. It then fully disables each account, including root, by locking their passwords and setting their expiration to an immediate end date. This dual action eliminates the chance for re-logins or ongoing unauthorized use, granting you peace of mind that the system remains inaccessible except through Level’s remote management.
#!/bin/bash
# This resource is provided as a convenience for Level users. We cannot
# guarantee it will work in all environments. Please test before deploying
# to your production environment. We welcome contributions to our community
# library
# Level Library
# https://level.io/library/script-linux-lock-device
# Initialize script-scoped error flag
script_errors=false
echo "Killing all user sessions..."
for user in $(who | awk '{print $1}' | sort | uniq); do
pkill -KILL -u "$user"
if [[ $? -ne 0 ]]; then
echo "ALERT: Failed to kill session for user $user."
script_errors=true
fi
done
echo "Fully locking all user accounts (SSH & local access)..."
for user in $(awk -F: '{if ($3 >= 1000 && $3 < 65534) print $1}' /etc/passwd); do
passwd -l "$user" &> /dev/null
usermod -L -e 1 "$user" &> /dev/null
if [[ $? -ne 0 ]]; then
echo "ALERT: Failed to lock user account $user."
script_errors=true
fi
done
echo "Locking root account..."
passwd -l root &> /dev/null
usermod -L -e 1 root &> /dev/null
if [[ $? -ne 0 ]]; then
echo "ALERT: Failed to lock root account."
script_errors=true
fi
if [[ "$script_errors" == true ]]; then
echo "ALERT: Errors occurred during execution. Exiting with code 1."
exit 1
fi
echo "All users have been kicked off and all accounts are completely locked."
Use cases.
Common ways to put this resource to work.
- Emergency lockdown after detecting suspicious activity
- Enhancing security for misplaced or stolen Linux devices
- Temporary lockout during sensitive maintenance tasks
- Restricting access for audits or compliance inspections
Recommendations.
Practical guidance for a reliable rollout.
- Thoroughly test this script on non-production systems before wider deployment
- Configure a script-based monitor in Level to run this script on-demand in response to security alerts
- Or, create an Automation in Level with a schedule trigger if you need routine lockdowns
- Validate after locking to ensure all necessary user sessions are terminated and accounts are disabled
- Pair with an unlock solution to easily restore access when the risk subsides