繁体   English   中英

如何限制并发 SSH 或 Dropbear 隧道连接

[英]How to limit concurrent SSH or Dropbear Tunnel connections

我需要将并发 SSH/Dropbear 隧道连接限制为每个用户 1 次登录。 我有一个脚本可以解决这个问题。 但这对我不起作用,因为当有很多用户时,它会变得饱和,并且需要很长时间才能踢出用户。 这个脚本的另一个问题是,如果用户注销并重新登录,它会被检测为多登录。 Maxlogins 和 MaxSessions 在 Dropbear 上不起作用。 以下是我正在使用的脚本:

#!/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

建议:

  1. journalctl -r非常昂贵。 journalctl限制为自上次搜索以来的时间。
  2. USER=$(...)PID=$(...)一致。 用单个awk命令替换printfsed命令。
  3. 研究pgreppkill命令。
  4. 将文件$PIDFILE $AUTHFILE $USERS替换为数组变量(研究readarray命令)。
  5. 虽然$AUTHFILE上的循环可以实现为 bash 数组上的循环。
  6. $USERS上的循环(包括内部循环)可以实现为 bash 数组上的循环。
  7. curl命令可能非常昂贵。 您不会检查每个curl请求的响应。 在后台运行curl ,如果可能的话,为所有用户并行运行。

如果您将$AUTHFILE中的示例行作为示例输入行放入问题中,那么善良的 SO 成员可以提供更多帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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