Skip to content

Instantly share code, notes, and snippets.

@RagingRoosevelt
Last active December 31, 2024 11:13
Show Gist options
  • Save RagingRoosevelt/5964bb03005d71e17611e21916860058 to your computer and use it in GitHub Desktop.
Save RagingRoosevelt/5964bb03005d71e17611e21916860058 to your computer and use it in GitHub Desktop.
Shell script to help with locking linux session, similar to Cold Turkey. Validated in Pop!_OS 22.04
#!/usr/bin/bash
# Figure out the current file name and path
# https://stackoverflow.com/a/4774063
script_path="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
script_filename=${0##*/}
script_full_path=$script_path/$script_filename
# Shows the help page for this script
show_help() {
cat << EOF
USAGE: $script_filename [logs] [tail] [help]
Running with no arguments will lock all active sessions.
--user <username> Lock user's active sessions
logs Searches /var/log/syslog for mention of this script
tail Tails /var/log/syslog, searching for mention of this script
help Display this help and exit
Register this script as a cron job by running
sudo crontab -u $USER -e
and inserting the following records:
*/5 0-5 * * 1-5 /bin/bash -c "$script_full_path --user $USER"
*/5 2-5 * * 6,0 /bin/bash -c "$script_full_path --user $USER"
EOF
}
# Tails the syslog for mention of this script, hopefully CRON mentions it
logs_tail() {
tail -f /var/log/syslog | grep "$script_full_path"
}
# Searches the syslog for mention of this script, hopefully CRON mentions it
logs_cat() {
echo Searching /var/log/syslog for $script_full_path...
grep "$script_full_path" /var/log/syslog
}
# Uses loginctl to search for sessions belonging to active user
# then, for each, locks them
run_main() {
if [ $1 == "" ]
then
loginctl lock-sessions
else
USER=$1
echo Looking for active sessions for user $USER...
for session in $(loginctl show-user $USER -p Sessions --value); do
session_user=$(loginctl show-session $session --value -p Name)
session_type=$(loginctl show-session $session --value -p Type)
echo ...found $session_type session with ID=$session belonging to $session_user. Locking...
loginctl lock-session $session
done
fi
}
# Parse CLI options
while :; do
case $1 in
help|-h|--help|-\?)
show_help
exit
;;
logs)
logs_cat
exit
;;
tail)
logs_tail
exit
;;
--user)
if [ "$2" == "" ]
then
printf 'WARN: No argument provided for option: --user. Run `%s help` to view flags\n' "$script_filename" >&2
else
run_main $2
fi
exit
;;
-?*)
printf 'WARN: Unknown option: %s. Run `%s help` to view flags.\n' "$1" "$script_filename" >&2
exit
;;
*)
if [ "$1" == "" ]
then
run_main
exit
else
printf 'WARN: Unknown argument: "%s". Run `%s help` to view flags.\n' "$1" "$script_filename" >&2
exit
fi
;;
esac
shift
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment