Shell 脚本,记录用户的用户名、执行的命令行以及IP地址

实现一个 Shell 脚本,记录用户的用户名、执行的命令行以及IP地址,并将这些信息输出到一个文件中,可以采用如下策略。此脚本假设是用于记录 SSH 登录会话中执行的命令。这种方法通常涉及修改 .bashrcbash_profile 文件来捕捉命令执行信息,并利用环境变量来获取用户名和IP地址。

1. 创建脚本来记录命令

首先,创建一个脚本文件 log_commands.sh,该脚本会被 .bashrc 调用以记录每个命令的执行:

#!/bin/bash

# log_commands.sh
log_file="/var/log/command_log.log"

# Function to append data to log
log_command() {
    local user=$USER
    local ip=$SSH_CLIENT
    [ -z "$ip" ] && ip="LOCAL"

    # Extract just the IP address (if not local)
    [ "$ip" != "LOCAL" ] && ip=$(echo $ip | awk '{print $1}')

    # Capture the command line but ignore the history number
    local cmd=$(history 1 | sed 's/^[ ]*[0-9]\+[ ]*//')

    # Append to the log file
    echo "$user : $cmd : $ip" >> $log_file
}

# Trap the DEBUG signal and log every command executed
trap log_command DEBUG

2. 修改用户的 .bashrc

在用户的 home 目录下的 .bashrc 文件中,添加以下行以确保每次打开一个新的 shell 时都会调用这个脚本:

# Append to the end of .bashrc
source /path/to/log_commands.sh

确保将 /path/to/log_commands.sh 替换为脚本实际的路径.

3. 设置合适的权限和拥有者

确保日志文件 /var/log/command_log.log 可以被脚本写入:

touch /var/log/command_log.log
chmod 662 /var/log/command_log.log
chown root:adm /var/log/command_log.log

4. 重新加载 .bashrc

source ~/.bashrc

注意

  • 本方法会记录所有通过 Bash 执行的命令。对于通过其他方式(如直接由程序执行的命令)可能不会被记录。

  • 这种方法可能会对系统性能产生轻微影响,特别是在命令执行非常频繁的环境中。

  • 确保 /var/log/command_log.log 的安全性,避免敏感信息泄露。

通过这种方法,可以基本实现对用户命令执行的记录,包括用户名、命令行和来源IP地址。

文章作者: Administrator
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 IKKO
喜欢就支持一下吧