Skip to content

Instantly share code, notes, and snippets.

@khavari
Last active June 11, 2026 11:55
Show Gist options
  • Select an option

  • Save khavari/571367027001aed49c3cc1d13a762b5b to your computer and use it in GitHub Desktop.

Select an option

Save khavari/571367027001aed49c3cc1d13a762b5b to your computer and use it in GitHub Desktop.
ssh_session_limit.md

SSH Session Limit Script

This script is used to limit the number of SSH sessions per user on a Linux system.

Create the script file:

sudo nano /usr/local/bin/ssh-limit.sh

Script content:

#!/bin/bash

user="$PAM_USER"

declare -A limits

limits=(
  ["root"]=10
  ["m.khavari"]=2
  ["others"]=1
)

limit=${limits[$user]}

if [ -z "$limit" ]; then
    limit=${limits["others"]}
fi

count=$(loginctl list-sessions --no-legend | awk -v u="$user" '$0 ~ u && $0 ~ / user / {c++} END {print c+0}')

if [ "$count" -ge "$limit" ]; then
    echo "SSH limit reached for $user (limit=$limit)"
    exit 1
fi

exit 0

Open SSH PAM configuration file:

sudo nano /etc/pam.d/sshd

The following line should be placed at the top of the file:

auth required pam_exec.so /usr/local/bin/ssh-limit.sh
or
session required pam_exec.so /usr/local/bin/ssh-limit.sh

Restart SSH service:

sudo systemctl restart ssh

User commands:

sudo pkill -9 -u username
sudo deluser --remove-home username
sudo adduser --allow-bad-names username
sudouseradd -m -s /usr/sbin/nologin username
 
sudo passwd username
awk -F: '$3 >= 1000 {printf "%-20s -> %s\n", $1, $7}' /etc/passwd
cat /etc/passwd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment