我在每次 ssh 登录时运行自定义脚本,以通知我是否存在尚未添加到自定义白名单的未知 IP 地址的登录。我在用着pam_exec.so每当用户登录时检查这一点。到目前为止,这工作正常,每当我登录时我都会收到我想要的通知,并且我自己的 IP 目前不在我定义的白名单中。
唯一的问题是我的脚本中有一个 for 循环,它应该告诉我服务器上存在哪些网站配置。为此,它会尝试获取所有文件/etc/apache2/sites-enabled。由于目前有一堆具有非描述性主机名的服务器,因此当我收到通知时知道其上正在运行什么会很方便。当我手动运行脚本时,没有问题,但当我使用 pam 自动化它时,带有配置名称的字符串显示为空。
有什么办法可以获取文件名吗?
以下是脚本、其权限设置以及我添加到 pam 配置中以使其正常工作的行:
/root/sh/登录通知.sh:
-rws--x--x 1 root root 1296 六月 14 日 07:45 登录-notify.sh*
#!/bin/sh
# Change sender depending on where the notification should go
sender="[email protected]"
target="[email protected]"
client_ip="${PAM_RHOST%% *}"
user=$PAM_USER
# Check if the session is open
if [ "$PAM_TYPE" != "close_session" ]; then
# Check if client ip is on the whitelist
if grep -Fxq "$client_ip" /etc/ssh_ip_whitelist; then
:
else
host="`hostname`"
# Get all active website configurations on the server
host_websites=""
for entry in /etc/apache2/sites-enabled/*
do
config_name="$(basename $entry)"
host_websites+="\n${config_name}"
done
subject="SSH Login: user $user from $client_ip on $host"
# Message to send, e.g. the current environment variables.
message="A new ssh login has been detected:\nhost - $host\nuser - $user\nip - $client_ip\n\nThe following website configurations exist on this server: $host_websites\n\nIf you trust this IP, please ask your server administrator to add it to the file /etc/ssh_ip_whitelist on this server. To quickly add an IP, connect to the server, change to root user and use:\n\necho \"<trusted ip>\" >> /etc/ssh_ip_whitelist"
# Send the email
echo "Subject: $subject\n$message"|/usr/sbin/sendmail -r $sender -t $target
fi
fi
/etc/pam.d/sshd:
session optional pam_exec.so seteuid /root/sh/login-notify.sh