I've decided to elaborate and test the Ravexina's idea. It works and it is effective if you want to restrict the number of established ssh connections at all.
First I found when the ssh daemon is running without any connection there is one sshd
process. For each new connection two new sshd
processes are created. So if you want limit of 20 connections the threshold should be 41 (1+2x20) instead of 20.
Then I've created an executable file, named /usr/local/bin/limit-sshd
, that looks as follow:
#!/bin/sh
if [ "$(pgrep -cx sshd)" -gt 7 ]
then
echo '\nThe limit was reached!\n'
pkill -xn sshd
fi
- The threshold here is 7, respectively only 3 connection could be established and the rest will be dropped.
Finally I've added the following directive to /etc/ssh/sshd_config
:
ForceCommand /usr/local/bin/limit-sshd; $SHELL
- The variable
$SHELL
will execute the default user's shell.
- An unwanted effect is that the greeting message is not longer available.
- Do not forget to restart the ssh daemon:
sudo systemctl restart sshd.service
Here is how this works (click on the image to see an animated demo):
Further, I realised we do not need to kill anything, if we modify the script in this way:
#!/bin/sh
if [ "$(pgrep -cx sshd)" -gt 7 ]
then
echo '\nThe limit was reached!\n'
exit # This line is not mandatory
else
eval "$SHELL"
fi
And respectively /etc/ssh/sshd_config
in this way:
ForceCommand /usr/local/bin/limit-sshd
MaxSessions
field/etc/sshd_config
, or is this a Ubuntu bug?