简体   繁体   中英

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

Suggestions:

  1. journalctl -r is very expensive. Limit journalctl to time since last search.
  2. Line with USER=$(...) and PID=$(...) . Replace printf and sed commands, with single awk command.
  3. Research pgrep and pkill commaonds.
  4. Replace file $PIDFILE $AUTHFILE $USERS with array variables (research readarray command).
  5. While loop over $AUTHFILE could be implemented as loop over bash array.
  6. While loop over $USERS (including internal loop) could be implemented as loop over bash array.
  7. curl command might be very expensive. You do not check the response from each curl request. Run curl in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM