Bash script to limit the number of logins

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
12
down vote

favorite
3












My company has the requirement that I have one server application running, which all users accessing it via putty terminal. I want to write a shell script that only 20 putty terminal should be open. If 21st terminal open then I want to close that terminal immediately.



How can I achieve this?



Please help me.










share|improve this question



















  • 3




    Set the max number connections allowed access in ssh to 20 on the server in the MaxSessions field
    – George Udosen
    Aug 29 at 10:03







  • 2




    If your corporation has a policy of 20 maximum sessions and the default is 10 (as the highest voted answer says), why did your company raise the number of allowable sessions > 20 in /etc/sshd_config, or is this a Ubuntu bug?
    – WinEunuuchs2Unix
    Aug 30 at 0:51










  • If 21st terminal open then I want to close that terminal immediately So the 20 first connections can hog the server indefinitely?
    – xenoid
    Aug 30 at 12:26














up vote
12
down vote

favorite
3












My company has the requirement that I have one server application running, which all users accessing it via putty terminal. I want to write a shell script that only 20 putty terminal should be open. If 21st terminal open then I want to close that terminal immediately.



How can I achieve this?



Please help me.










share|improve this question



















  • 3




    Set the max number connections allowed access in ssh to 20 on the server in the MaxSessions field
    – George Udosen
    Aug 29 at 10:03







  • 2




    If your corporation has a policy of 20 maximum sessions and the default is 10 (as the highest voted answer says), why did your company raise the number of allowable sessions > 20 in /etc/sshd_config, or is this a Ubuntu bug?
    – WinEunuuchs2Unix
    Aug 30 at 0:51










  • If 21st terminal open then I want to close that terminal immediately So the 20 first connections can hog the server indefinitely?
    – xenoid
    Aug 30 at 12:26












up vote
12
down vote

favorite
3









up vote
12
down vote

favorite
3






3





My company has the requirement that I have one server application running, which all users accessing it via putty terminal. I want to write a shell script that only 20 putty terminal should be open. If 21st terminal open then I want to close that terminal immediately.



How can I achieve this?



Please help me.










share|improve this question















My company has the requirement that I have one server application running, which all users accessing it via putty terminal. I want to write a shell script that only 20 putty terminal should be open. If 21st terminal open then I want to close that terminal immediately.



How can I achieve this?



Please help me.







command-line bash scripts






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 31 at 10:55









Ravexina

28.3k146897




28.3k146897










asked Aug 29 at 9:58









vijay12289

613




613







  • 3




    Set the max number connections allowed access in ssh to 20 on the server in the MaxSessions field
    – George Udosen
    Aug 29 at 10:03







  • 2




    If your corporation has a policy of 20 maximum sessions and the default is 10 (as the highest voted answer says), why did your company raise the number of allowable sessions > 20 in /etc/sshd_config, or is this a Ubuntu bug?
    – WinEunuuchs2Unix
    Aug 30 at 0:51










  • If 21st terminal open then I want to close that terminal immediately So the 20 first connections can hog the server indefinitely?
    – xenoid
    Aug 30 at 12:26












  • 3




    Set the max number connections allowed access in ssh to 20 on the server in the MaxSessions field
    – George Udosen
    Aug 29 at 10:03







  • 2




    If your corporation has a policy of 20 maximum sessions and the default is 10 (as the highest voted answer says), why did your company raise the number of allowable sessions > 20 in /etc/sshd_config, or is this a Ubuntu bug?
    – WinEunuuchs2Unix
    Aug 30 at 0:51










  • If 21st terminal open then I want to close that terminal immediately So the 20 first connections can hog the server indefinitely?
    – xenoid
    Aug 30 at 12:26







3




3




Set the max number connections allowed access in ssh to 20 on the server in the MaxSessions field
– George Udosen
Aug 29 at 10:03





Set the max number connections allowed access in ssh to 20 on the server in the MaxSessions field
– George Udosen
Aug 29 at 10:03





2




2




If your corporation has a policy of 20 maximum sessions and the default is 10 (as the highest voted answer says), why did your company raise the number of allowable sessions > 20 in /etc/sshd_config, or is this a Ubuntu bug?
– WinEunuuchs2Unix
Aug 30 at 0:51




If your corporation has a policy of 20 maximum sessions and the default is 10 (as the highest voted answer says), why did your company raise the number of allowable sessions > 20 in /etc/sshd_config, or is this a Ubuntu bug?
– WinEunuuchs2Unix
Aug 30 at 0:51












If 21st terminal open then I want to close that terminal immediately So the 20 first connections can hog the server indefinitely?
– xenoid
Aug 30 at 12:26




If 21st terminal open then I want to close that terminal immediately So the 20 first connections can hog the server indefinitely?
– xenoid
Aug 30 at 12:26










4 Answers
4






active

oldest

votes

















up vote
24
down vote













Edit your /etc/sshd_config on the server side and change the line:



#MaxSessions 10


to



MaxSessions 20


See man sshd_config:



 MaxSessions
Specifies the maximum number of open shell, login or subsystem
(e.g. sftp) sessions permitted per network connection. Multiple
sessions may be established by clients that support connection
multiplexing. Setting MaxSessions to 1 will effectively disable
session multiplexing, whereas setting it to 0 will prevent all
shell, login and subsystem sessions while still permitting for-
warding. The default is 10.





share|improve this answer






















  • yeah its works, bit late to add it as answer.
    – rɑːdʒɑ
    Aug 29 at 10:13






  • 2




    I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
    – WinEunuuchs2Unix
    Aug 30 at 1:14






  • 2




    You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
    – allo
    Aug 30 at 8:56











  • @allo this information you got from OP?
    – George Udosen
    Aug 30 at 9:21






  • 1




    @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
    – Joe Lee-Moyet
    Aug 30 at 16:44

















up vote
5
down vote













George's solution works fine however you asked for a bash script...



So consider this one for other situations when there is no option like MaxSessions of sshd, then you can use something like this:



if [ "$(pgrep -cx processName)" -gt 20 ]; then pkill -xn processName; fi; 


Which pkill -n will kill the newest instance of processName.



The correct solution for this special situation is George's answer.






share|improve this answer




















  • Wouldn't this also prevent subprocesses?
    – RonJohn
    Aug 29 at 15:56










  • Yeah it causes sub-process to be killed too.
    – Ravexina
    Aug 29 at 16:11






  • 2




    Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
    – RonJohn
    Aug 29 at 16:26






  • 1




    @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
    – Ravexina
    Aug 29 at 16:39










  • Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
    – George Udosen
    Aug 30 at 6:46

















up vote
4
down vote













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):



enter image description here



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





share|improve this answer





























    up vote
    2
    down vote













    The question isn't clear. Let me tell first how do I understand it and in which way, IMO, it should be asked:




    We have local network where one server supplies a specific
    application. Our team access this application via ssh connection from
    their computers to the server by using PuTTY. Each team member has its
    own user account that is used to establish the ssh connections (or maybe: all team members use a common user account).



    The team members doesn't use the server for any other purposes and we want to limit the number of their ssh connections to 20, no matter how much connections are established yet by a particular user (or maybe: 20 connections per user).




    If that interpretation is correct, probably a correct way to fulfil the requirements is to create a user group, then add all user accounts to that group and limit the number of maxlogins via /etc/security/limits.conf.




    1. Create a group, called for example the-app-maxlogins, with group id 10 000:



      sudo groupadd -g 10000 the-app-maxlogins



    2. Add the users to that group - sudo adduser <user> <group>:



      for user in "user1" "user2" "user3"; do sudo adduser "$user" the-app-maxlogins; done



    3. Add the next line to /etc/security/limits.conf to limit the maxlogins of the entire group:



      %the-app-maxlogins - maxlogins 20


      Or add the following line to limit the maximum logins number per user of the group:



      @the-app-maxlogins - maxlogins 20



    4. Edit /etc/ssh/sshd_config and add the following lines to the bottom(!) of the file to disable session multiplexing for that group (probably this is not mandatory in that case):



      Match Group the-app-maxlogins
      MaxSessions 1



    This solution will limit the number the logins of the affected users no matter through ssh or tty. If you want to apply it for a certain user not for a group just add a line as the follow in limits.conf or place it into a separate .conf file within the directory /etc/security/limits.d/:



    username - maxlogins 20



    Simple explanation of the actual meaning of the directive MaxSessions is provided in this answer. The main source of the current answer is another answer under the same L&U's question.



    The other answer of mine, could provide workaround in some way, but it is a kind of fun rather than true solution.






    share|improve this answer






















      Your Answer







      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "89"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1070055%2fbash-script-to-limit-the-number-of-logins%23new-answer', 'question_page');

      );

      Post as a guest






























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      24
      down vote













      Edit your /etc/sshd_config on the server side and change the line:



      #MaxSessions 10


      to



      MaxSessions 20


      See man sshd_config:



       MaxSessions
      Specifies the maximum number of open shell, login or subsystem
      (e.g. sftp) sessions permitted per network connection. Multiple
      sessions may be established by clients that support connection
      multiplexing. Setting MaxSessions to 1 will effectively disable
      session multiplexing, whereas setting it to 0 will prevent all
      shell, login and subsystem sessions while still permitting for-
      warding. The default is 10.





      share|improve this answer






















      • yeah its works, bit late to add it as answer.
        – rɑːdʒɑ
        Aug 29 at 10:13






      • 2




        I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
        – WinEunuuchs2Unix
        Aug 30 at 1:14






      • 2




        You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
        – allo
        Aug 30 at 8:56











      • @allo this information you got from OP?
        – George Udosen
        Aug 30 at 9:21






      • 1




        @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
        – Joe Lee-Moyet
        Aug 30 at 16:44














      up vote
      24
      down vote













      Edit your /etc/sshd_config on the server side and change the line:



      #MaxSessions 10


      to



      MaxSessions 20


      See man sshd_config:



       MaxSessions
      Specifies the maximum number of open shell, login or subsystem
      (e.g. sftp) sessions permitted per network connection. Multiple
      sessions may be established by clients that support connection
      multiplexing. Setting MaxSessions to 1 will effectively disable
      session multiplexing, whereas setting it to 0 will prevent all
      shell, login and subsystem sessions while still permitting for-
      warding. The default is 10.





      share|improve this answer






















      • yeah its works, bit late to add it as answer.
        – rɑːdʒɑ
        Aug 29 at 10:13






      • 2




        I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
        – WinEunuuchs2Unix
        Aug 30 at 1:14






      • 2




        You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
        – allo
        Aug 30 at 8:56











      • @allo this information you got from OP?
        – George Udosen
        Aug 30 at 9:21






      • 1




        @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
        – Joe Lee-Moyet
        Aug 30 at 16:44












      up vote
      24
      down vote










      up vote
      24
      down vote









      Edit your /etc/sshd_config on the server side and change the line:



      #MaxSessions 10


      to



      MaxSessions 20


      See man sshd_config:



       MaxSessions
      Specifies the maximum number of open shell, login or subsystem
      (e.g. sftp) sessions permitted per network connection. Multiple
      sessions may be established by clients that support connection
      multiplexing. Setting MaxSessions to 1 will effectively disable
      session multiplexing, whereas setting it to 0 will prevent all
      shell, login and subsystem sessions while still permitting for-
      warding. The default is 10.





      share|improve this answer














      Edit your /etc/sshd_config on the server side and change the line:



      #MaxSessions 10


      to



      MaxSessions 20


      See man sshd_config:



       MaxSessions
      Specifies the maximum number of open shell, login or subsystem
      (e.g. sftp) sessions permitted per network connection. Multiple
      sessions may be established by clients that support connection
      multiplexing. Setting MaxSessions to 1 will effectively disable
      session multiplexing, whereas setting it to 0 will prevent all
      shell, login and subsystem sessions while still permitting for-
      warding. The default is 10.






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 29 at 10:13

























      answered Aug 29 at 10:08









      George Udosen

      17.3k93861




      17.3k93861











      • yeah its works, bit late to add it as answer.
        – rɑːdʒɑ
        Aug 29 at 10:13






      • 2




        I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
        – WinEunuuchs2Unix
        Aug 30 at 1:14






      • 2




        You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
        – allo
        Aug 30 at 8:56











      • @allo this information you got from OP?
        – George Udosen
        Aug 30 at 9:21






      • 1




        @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
        – Joe Lee-Moyet
        Aug 30 at 16:44
















      • yeah its works, bit late to add it as answer.
        – rɑːdʒɑ
        Aug 29 at 10:13






      • 2




        I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
        – WinEunuuchs2Unix
        Aug 30 at 1:14






      • 2




        You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
        – allo
        Aug 30 at 8:56











      • @allo this information you got from OP?
        – George Udosen
        Aug 30 at 9:21






      • 1




        @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
        – Joe Lee-Moyet
        Aug 30 at 16:44















      yeah its works, bit late to add it as answer.
      – rɑːdʒɑ
      Aug 29 at 10:13




      yeah its works, bit late to add it as answer.
      – rɑːdʒɑ
      Aug 29 at 10:13




      2




      2




      I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
      – WinEunuuchs2Unix
      Aug 30 at 1:14




      I've been meaning to setup SSSH thingy on one of my old laptops for awhile now. Is the man page saying that by default only 10 users can sign into the server? Even back in the 80's we could have a hundred users sign into an IBM S/36 mini-computer with 2 MB of RAM.
      – WinEunuuchs2Unix
      Aug 30 at 1:14




      2




      2




      You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
      – allo
      Aug 30 at 8:56





      You are confusing sessions as in open terminals (see OP) with sessions inside a SSH connection. The setting you mention is about how many "sub-connections" are allowed by a single ssh-connection. So running 30 "ssh" commands is no problem even with MaxSessions 20. The sessions mentioned there are about things like port-forwardings (and even having more than one shell open) using the same connection, not about the number of logins on the system.
      – allo
      Aug 30 at 8:56













      @allo this information you got from OP?
      – George Udosen
      Aug 30 at 9:21




      @allo this information you got from OP?
      – George Udosen
      Aug 30 at 9:21




      1




      1




      @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
      – Joe Lee-Moyet
      Aug 30 at 16:44




      @allo is correct here, MaxSessions refers to session multiplexing over a single TCP connection. Unless all of OP's users are doing strange things to share a single TCP connection to the server this limit won't affect them. I've just verified this myself by setting a low MaxSessions limit on a server and opening more than that many connections to it.
      – Joe Lee-Moyet
      Aug 30 at 16:44












      up vote
      5
      down vote













      George's solution works fine however you asked for a bash script...



      So consider this one for other situations when there is no option like MaxSessions of sshd, then you can use something like this:



      if [ "$(pgrep -cx processName)" -gt 20 ]; then pkill -xn processName; fi; 


      Which pkill -n will kill the newest instance of processName.



      The correct solution for this special situation is George's answer.






      share|improve this answer




















      • Wouldn't this also prevent subprocesses?
        – RonJohn
        Aug 29 at 15:56










      • Yeah it causes sub-process to be killed too.
        – Ravexina
        Aug 29 at 16:11






      • 2




        Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
        – RonJohn
        Aug 29 at 16:26






      • 1




        @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
        – Ravexina
        Aug 29 at 16:39










      • Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
        – George Udosen
        Aug 30 at 6:46














      up vote
      5
      down vote













      George's solution works fine however you asked for a bash script...



      So consider this one for other situations when there is no option like MaxSessions of sshd, then you can use something like this:



      if [ "$(pgrep -cx processName)" -gt 20 ]; then pkill -xn processName; fi; 


      Which pkill -n will kill the newest instance of processName.



      The correct solution for this special situation is George's answer.






      share|improve this answer




















      • Wouldn't this also prevent subprocesses?
        – RonJohn
        Aug 29 at 15:56










      • Yeah it causes sub-process to be killed too.
        – Ravexina
        Aug 29 at 16:11






      • 2




        Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
        – RonJohn
        Aug 29 at 16:26






      • 1




        @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
        – Ravexina
        Aug 29 at 16:39










      • Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
        – George Udosen
        Aug 30 at 6:46












      up vote
      5
      down vote










      up vote
      5
      down vote









      George's solution works fine however you asked for a bash script...



      So consider this one for other situations when there is no option like MaxSessions of sshd, then you can use something like this:



      if [ "$(pgrep -cx processName)" -gt 20 ]; then pkill -xn processName; fi; 


      Which pkill -n will kill the newest instance of processName.



      The correct solution for this special situation is George's answer.






      share|improve this answer












      George's solution works fine however you asked for a bash script...



      So consider this one for other situations when there is no option like MaxSessions of sshd, then you can use something like this:



      if [ "$(pgrep -cx processName)" -gt 20 ]; then pkill -xn processName; fi; 


      Which pkill -n will kill the newest instance of processName.



      The correct solution for this special situation is George's answer.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Aug 29 at 13:59









      Ravexina

      28.3k146897




      28.3k146897











      • Wouldn't this also prevent subprocesses?
        – RonJohn
        Aug 29 at 15:56










      • Yeah it causes sub-process to be killed too.
        – Ravexina
        Aug 29 at 16:11






      • 2




        Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
        – RonJohn
        Aug 29 at 16:26






      • 1




        @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
        – Ravexina
        Aug 29 at 16:39










      • Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
        – George Udosen
        Aug 30 at 6:46
















      • Wouldn't this also prevent subprocesses?
        – RonJohn
        Aug 29 at 15:56










      • Yeah it causes sub-process to be killed too.
        – Ravexina
        Aug 29 at 16:11






      • 2




        Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
        – RonJohn
        Aug 29 at 16:26






      • 1




        @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
        – Ravexina
        Aug 29 at 16:39










      • Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
        – George Udosen
        Aug 30 at 6:46















      Wouldn't this also prevent subprocesses?
      – RonJohn
      Aug 29 at 15:56




      Wouldn't this also prevent subprocesses?
      – RonJohn
      Aug 29 at 15:56












      Yeah it causes sub-process to be killed too.
      – Ravexina
      Aug 29 at 16:11




      Yeah it causes sub-process to be killed too.
      – Ravexina
      Aug 29 at 16:11




      2




      2




      Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
      – RonJohn
      Aug 29 at 16:26




      Then -- given that bash forks lots of subprocesses, and they want to limit users, not processes -- this doesn't appear to be a useful answer.
      – RonJohn
      Aug 29 at 16:26




      1




      1




      @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
      – Ravexina
      Aug 29 at 16:39




      @RonJohn It was a useful answer corresponding to the user requirements (A script that closes a process immediately) and for other users coming from search engines (a general answer to the title) until you edited the question.
      – Ravexina
      Aug 29 at 16:39












      Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
      – George Udosen
      Aug 30 at 6:46




      Let me come in here. I also know that this place directs users to the right path based on the questions asked. If OP asks a question and the right answer (based on OP's question) isn't necessarily the best practice or right approach I think any one has the right to state this or give answers inline with that observation. I don't really think we should take the option of deciding what answer is the best let OP decide and I love to see many options from well informed site members. Please lets always have a constructive debate it helps me if not any other person!
      – George Udosen
      Aug 30 at 6:46










      up vote
      4
      down vote













      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):



      enter image description here



      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





      share|improve this answer


























        up vote
        4
        down vote













        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):



        enter image description here



        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





        share|improve this answer
























          up vote
          4
          down vote










          up vote
          4
          down vote









          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):



          enter image description here



          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





          share|improve this answer














          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):



          enter image description here



          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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 30 at 13:16

























          answered Aug 29 at 22:17









          pa4080

          12.3k52256




          12.3k52256




















              up vote
              2
              down vote













              The question isn't clear. Let me tell first how do I understand it and in which way, IMO, it should be asked:




              We have local network where one server supplies a specific
              application. Our team access this application via ssh connection from
              their computers to the server by using PuTTY. Each team member has its
              own user account that is used to establish the ssh connections (or maybe: all team members use a common user account).



              The team members doesn't use the server for any other purposes and we want to limit the number of their ssh connections to 20, no matter how much connections are established yet by a particular user (or maybe: 20 connections per user).




              If that interpretation is correct, probably a correct way to fulfil the requirements is to create a user group, then add all user accounts to that group and limit the number of maxlogins via /etc/security/limits.conf.




              1. Create a group, called for example the-app-maxlogins, with group id 10 000:



                sudo groupadd -g 10000 the-app-maxlogins



              2. Add the users to that group - sudo adduser <user> <group>:



                for user in "user1" "user2" "user3"; do sudo adduser "$user" the-app-maxlogins; done



              3. Add the next line to /etc/security/limits.conf to limit the maxlogins of the entire group:



                %the-app-maxlogins - maxlogins 20


                Or add the following line to limit the maximum logins number per user of the group:



                @the-app-maxlogins - maxlogins 20



              4. Edit /etc/ssh/sshd_config and add the following lines to the bottom(!) of the file to disable session multiplexing for that group (probably this is not mandatory in that case):



                Match Group the-app-maxlogins
                MaxSessions 1



              This solution will limit the number the logins of the affected users no matter through ssh or tty. If you want to apply it for a certain user not for a group just add a line as the follow in limits.conf or place it into a separate .conf file within the directory /etc/security/limits.d/:



              username - maxlogins 20



              Simple explanation of the actual meaning of the directive MaxSessions is provided in this answer. The main source of the current answer is another answer under the same L&U's question.



              The other answer of mine, could provide workaround in some way, but it is a kind of fun rather than true solution.






              share|improve this answer


























                up vote
                2
                down vote













                The question isn't clear. Let me tell first how do I understand it and in which way, IMO, it should be asked:




                We have local network where one server supplies a specific
                application. Our team access this application via ssh connection from
                their computers to the server by using PuTTY. Each team member has its
                own user account that is used to establish the ssh connections (or maybe: all team members use a common user account).



                The team members doesn't use the server for any other purposes and we want to limit the number of their ssh connections to 20, no matter how much connections are established yet by a particular user (or maybe: 20 connections per user).




                If that interpretation is correct, probably a correct way to fulfil the requirements is to create a user group, then add all user accounts to that group and limit the number of maxlogins via /etc/security/limits.conf.




                1. Create a group, called for example the-app-maxlogins, with group id 10 000:



                  sudo groupadd -g 10000 the-app-maxlogins



                2. Add the users to that group - sudo adduser <user> <group>:



                  for user in "user1" "user2" "user3"; do sudo adduser "$user" the-app-maxlogins; done



                3. Add the next line to /etc/security/limits.conf to limit the maxlogins of the entire group:



                  %the-app-maxlogins - maxlogins 20


                  Or add the following line to limit the maximum logins number per user of the group:



                  @the-app-maxlogins - maxlogins 20



                4. Edit /etc/ssh/sshd_config and add the following lines to the bottom(!) of the file to disable session multiplexing for that group (probably this is not mandatory in that case):



                  Match Group the-app-maxlogins
                  MaxSessions 1



                This solution will limit the number the logins of the affected users no matter through ssh or tty. If you want to apply it for a certain user not for a group just add a line as the follow in limits.conf or place it into a separate .conf file within the directory /etc/security/limits.d/:



                username - maxlogins 20



                Simple explanation of the actual meaning of the directive MaxSessions is provided in this answer. The main source of the current answer is another answer under the same L&U's question.



                The other answer of mine, could provide workaround in some way, but it is a kind of fun rather than true solution.






                share|improve this answer
























                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  The question isn't clear. Let me tell first how do I understand it and in which way, IMO, it should be asked:




                  We have local network where one server supplies a specific
                  application. Our team access this application via ssh connection from
                  their computers to the server by using PuTTY. Each team member has its
                  own user account that is used to establish the ssh connections (or maybe: all team members use a common user account).



                  The team members doesn't use the server for any other purposes and we want to limit the number of their ssh connections to 20, no matter how much connections are established yet by a particular user (or maybe: 20 connections per user).




                  If that interpretation is correct, probably a correct way to fulfil the requirements is to create a user group, then add all user accounts to that group and limit the number of maxlogins via /etc/security/limits.conf.




                  1. Create a group, called for example the-app-maxlogins, with group id 10 000:



                    sudo groupadd -g 10000 the-app-maxlogins



                  2. Add the users to that group - sudo adduser <user> <group>:



                    for user in "user1" "user2" "user3"; do sudo adduser "$user" the-app-maxlogins; done



                  3. Add the next line to /etc/security/limits.conf to limit the maxlogins of the entire group:



                    %the-app-maxlogins - maxlogins 20


                    Or add the following line to limit the maximum logins number per user of the group:



                    @the-app-maxlogins - maxlogins 20



                  4. Edit /etc/ssh/sshd_config and add the following lines to the bottom(!) of the file to disable session multiplexing for that group (probably this is not mandatory in that case):



                    Match Group the-app-maxlogins
                    MaxSessions 1



                  This solution will limit the number the logins of the affected users no matter through ssh or tty. If you want to apply it for a certain user not for a group just add a line as the follow in limits.conf or place it into a separate .conf file within the directory /etc/security/limits.d/:



                  username - maxlogins 20



                  Simple explanation of the actual meaning of the directive MaxSessions is provided in this answer. The main source of the current answer is another answer under the same L&U's question.



                  The other answer of mine, could provide workaround in some way, but it is a kind of fun rather than true solution.






                  share|improve this answer














                  The question isn't clear. Let me tell first how do I understand it and in which way, IMO, it should be asked:




                  We have local network where one server supplies a specific
                  application. Our team access this application via ssh connection from
                  their computers to the server by using PuTTY. Each team member has its
                  own user account that is used to establish the ssh connections (or maybe: all team members use a common user account).



                  The team members doesn't use the server for any other purposes and we want to limit the number of their ssh connections to 20, no matter how much connections are established yet by a particular user (or maybe: 20 connections per user).




                  If that interpretation is correct, probably a correct way to fulfil the requirements is to create a user group, then add all user accounts to that group and limit the number of maxlogins via /etc/security/limits.conf.




                  1. Create a group, called for example the-app-maxlogins, with group id 10 000:



                    sudo groupadd -g 10000 the-app-maxlogins



                  2. Add the users to that group - sudo adduser <user> <group>:



                    for user in "user1" "user2" "user3"; do sudo adduser "$user" the-app-maxlogins; done



                  3. Add the next line to /etc/security/limits.conf to limit the maxlogins of the entire group:



                    %the-app-maxlogins - maxlogins 20


                    Or add the following line to limit the maximum logins number per user of the group:



                    @the-app-maxlogins - maxlogins 20



                  4. Edit /etc/ssh/sshd_config and add the following lines to the bottom(!) of the file to disable session multiplexing for that group (probably this is not mandatory in that case):



                    Match Group the-app-maxlogins
                    MaxSessions 1



                  This solution will limit the number the logins of the affected users no matter through ssh or tty. If you want to apply it for a certain user not for a group just add a line as the follow in limits.conf or place it into a separate .conf file within the directory /etc/security/limits.d/:



                  username - maxlogins 20



                  Simple explanation of the actual meaning of the directive MaxSessions is provided in this answer. The main source of the current answer is another answer under the same L&U's question.



                  The other answer of mine, could provide workaround in some way, but it is a kind of fun rather than true solution.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 30 at 13:28

























                  answered Aug 30 at 12:18









                  pa4080

                  12.3k52256




                  12.3k52256



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1070055%2fbash-script-to-limit-the-number-of-logins%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Popular posts from this blog

                      How to check contact read email or not when send email to Individual?

                      Bahrain

                      Postfix configuration issue with fips on centos 7; mailgun relay