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