'How to limit concurrent SSH or Dropbear Tunnel connections
I need to limit concurrent SSH/Dropbear Tunnel connections to 1 login per user. I have a script that takes care of that. But it doesn't work for me because when there are many users it becomes saturated and it takes a long time to kick the users. Another problem with this script is that if the user logs out and logs back in it is detected as multilogin. Maxlogins and MaxSessions does not work on Dropbear. Below is the script I am using:
#!/bin/bash
# This script locates all users who have multiple active dropbear
# processes and kills processes in excess of one for each user.
if [ "$EUID" -ne 0 ]; then
printf "Please run as root.\n"
exit
fi
IFS=+
while true; do
PIDFILE=$(mktemp)
AUTHFILE=$(mktemp)
USERS=$(mktemp)
ps aux | grep dropbear | grep -v grep | awk 'BEGIN{} {print $2}' > $PIDFILE
journalctl -r | grep dropbear | grep auth > $AUTHFILE
while read LINE; do
USER=$(printf "%s" $LINE | sed "s/^.* '//" | sed "s/'.*$//" -)
PID=$(printf "%s" $LINE | sed "s/^.*\[//" | sed "s/].*$//" -)
if grep -Fxq $(printf "%s" $USER) $USERS; then
:
else
printf "%s\n" $USER >> $USERS
fi
USERFILE=$(printf "/tmp/%s" $USER)
if [ ! -f $USERFILE ]; then
touch $USERFILE
fi
if grep -Fxq $(printf "%s" $PID) $PIDFILE; then
printf "%s\n" $PID >> $USERFILE
else
:
fi
done < $AUTHFILE
while read USER; do
i=1
while read PID; do
if [ $i -gt 1 ]; then
printf "Kill PID %s of user %s\n" $PID $USER
kill -9 $(printf "%s" $PID)
curl -k "https://redesprivadasvirtuales.com/modules/servers/openvpn/vega.php?secret=DD8sPD&user=$USER"
else
:
fi
((i++))
done < $(printf "/tmp/%s" $USER)
rm $(printf "/tmp/%s" $USER)
done < $USERS
rm $PIDFILE
rm $AUTHFILE
rm $USERS
done
Solution 1:[1]
Suggestions:
journalctl -ris very expensive. Limitjournalctlto time since last search.- Line with
USER=$(...)andPID=$(...). Replaceprintfandsedcommands, with singleawkcommand. - Research
pgrepandpkillcommaonds. - Replace file
$PIDFILE$AUTHFILE$USERSwith array variables (researchreadarraycommand). - While loop over
$AUTHFILEcould be implemented as loop over bash array. - While loop over
$USERS(including internal loop) could be implemented as loop over bash array. curlcommand might be very expensive. You do not check the response from eachcurlrequest. Runcurlin background and if possible in parallel for all users.
Kind SO members could assist more, if you put sample lines from $AUTHFILE in the questions as sample input line.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
