在脚本中调用 tail 读取 /var/log/syslog 会导致 syslog 中出现“权限被拒绝”

在脚本中调用 tail 读取 /var/log/syslog 会导致 syslog 中出现“权限被拒绝”

当用户使用客户端连接连接到我的 openvpn 服务器时,此脚本将运行。运行时,它应检查 syslog 中最近的 50 条日志行以获取连接的配置文件的名称。

我遇到的问题是,当脚本尝试使用 tail 从 syslog 读取时,由于权限不足而被拒绝。以下是脚本本身的权限以及所有者的权限,myuser

ls -l /etc/openvpn/myscript.sh
-rwxr-xr-x 1 myuser adm 1274 

正在运行的groups myuser产物myuser : adm sudo因此myuser处于adm并且应该具有适当的权限才能读取/var/log/syslog

我已将其添加myuser ALL=(ALL) NOPASSWD: /etc/openvpn/myscript.sh到 sudoers 文件中,以备sudo tail脚本中所述。这并没有改变任何东西。

还有什么可能阻止该脚本访问/var/log/syslog

编辑:添加脚本的净化版本。

#!/bin/bash

\# Set the path to the OpenVPN log file
LOG_FILE=/var/log/syslog

\# Set the email settings
SMTP_SERVER="smtp server here"
SMTP_PORT="xxx"
FROM_ADDRESS="[email protected]"
TO_ADDRESS="[email protected]"
SUBJECT="Alert: OpenVPN Connection Established"
BODY1="A client has connected to the OpenVPN server using the profile: \""
BODY2="\". The source IP is: "
BODY3=". If you have not recently connected to the OpenVPN server from this IP, please remove the profile ASAP."


sendEmail() {
    logger "Starting email send.."
    # Get the last line of the OpenVPN log file
    LAST_LINE=$(sudo -u myuser tail -n 50 /var/log/syslog | grep -m 1 "Peer Connection Initiated")

    logger "Outside the if"
    logger "Last Line Contents --> $LAST_LINE"
    # Check if the last line of the log file contains "Peer Connection Initiated"
    if echo "$LAST_LINE" | grep -q "Peer Connection Initiated"; then
        logger "Inside the if"
        #extract profile name from brackets in string
        IP=$(echo "$LAST_LINE" | cut -d "]" -f4 | cut -d ":" -f1)
        PROFILE=$(echo "$LAST_LINE" | cut -d "]" -f2 | cut -d "[" -f2)
        BODY0="$BODY1$PROFILE$BODY2$IP$BODY3"
        # If the last line contains the string, send an email notification
        msmtp -a default $TO_ADDRESS <<EOF
From: $FROM_ADDRESS
To: $TO_ADDRESS
Subject: $SUBJECT

$BODY0
EOF

    fi
}

sendEmail

我确信这绝对不是最干净的脚本,因为我与 ChatGPT 合作创建了它。但希望这能有所帮助。

相关内容