我想阻止交互的和非交互式根据条件逻辑进行 ssh 登录。我需要测试用户名并给出错误消息。
使用 sftp(非交互式 ssh)的人也应该接受运气测试。
我该如何实现呢?我可以完全控制系统。
我尝试使用 sshd ForceCommand,但根据https://stackoverflow.com/a/33714333/746461它对 notty 不起作用。
我不熟悉 PAM,并且我怀疑在登录是交互式的情况下 PAM 是否可以输出自定义错误消息。
https://linuxhint.com/understanding_bash_shell_configuration_startup/表示带有选项的非交互式登录 shell--noprofile
可以绕过所有 bash 配置文件。这就是为什么我无法在那里写我的逻辑。
答案1
我明白了。我可以实现一个 PAM 模块来做到这一点。
将以下内容保存到文件/root/checkConnections
。
#! /bin/bash
limit=$1
c=$(pgrep -xcu $PAM_USER sshd)
if [[ $c -ge "$limit" ]]; then
echo "Max $limit ssh connections allowed, but you have $c."
exit 1
fi
然后在 /etc/pam.d/sshd 中添加
session required pam_exec.so stdout /root/checkConnections 5
pam_exec.so
执行shell脚本,stdout
将消息输出到用户终端。
当条件不满足的时候,效果是这样的。
$ ssh localhost
Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-74-generic x86_64)
94 updates can be installed immediately.
0 of these updates are security updates.
To see these additional updates run: apt list --upgradable
Max 5 ssh connections allowed, but you have 5.
/root/checkConnections failed: exit code 1
Last login: Thu Jun 24 12:19:27 2021 from 172.18.33.67
Connection to localhost closed.