在命令上运行 shell 脚本

在命令上运行 shell 脚本

我想在date -s <string>使用命令时运行 shell 脚本。例如,我想通过在 shell 脚本中执行以下命令将命令记录到文件 /tmp/user.log

logger -p user.notice "date -s command executed" -f /tmp/user.log

date -s <string>在 shell 上执行shell 脚本时如何运行该脚本?

为了更通用,我想当其他人在我的系统上发出特定的 Linux 命令时运行我的 shell 脚本。该怎么做?

答案1

换个说法,您想知道何时有人试图设置系统时间。这正是子系统的用途audit……它允许您审核特定系统调用的执行情况。在这种情况下,您想知道何时有人调用可以更改系统时间的各种系统调用。通过使用子系统audit,您可以获得一个有效的解决方案,无论有人调用命令/bin/date还是他们自己本地构建的命令版本。

请参阅auditd(8)audit.rules(7)获取规则语法的完整描述,以及审计时间更改操作的示例,您可以在示例nispom.rules文件中查找“time-change”。您可以在本地系统上找到它,也可以在这里找到它:

有关audit子系统的更多信息(文档有点难以获得):

答案2

你不能轻易地阻止用户运行他自己版本的程序,但如果你假设用户没有恶意,这很容易:

  1. 创建一个包装脚本,记录该程序然后运行它(使用原始参数)
  2. 确保包装器替换用户路径中的原始程序。

您可以使用别名让用户使用包装器,或者您可以简单地移动/重命名原始程序并将包装器放在原始位置。

如果您只想记录某些执行,请在包装脚本中使用正则表达式。

答案3

非常感谢serverfault朋友们的回答。

在你们的帮助下,我想我已经找到了问题的答案。但是如果其中有任何错误或需要改进,你们能帮我解决吗?我来回答一下。

这些就是我所做的事情。

i).datewrapper.sh在 /etc 中创建一个脚本,代码如下

#! /bin/bash

# wrapper script for the date command.
# whenever the date -s command is issued, it will be logged.

# executing the date command first with parameter list if any
date $@

# check whether the date command executed successfully
if [ "$?" == "0" ] ; then
   for param in $@ ; do
      # if "-s" option is used, log it
      if [ "$param" == "-s" ] ; then
         # user.notice logs the message to /tmp/log/user.log
         # as per the commands in /etc/syslog-ng/syslog-ng.conf
         logger -p user.notice "New date set"
         break
      fi
   done
fi

exit 0

ii). chmod a+x /etc/datewrapper.sh ; 别名 date='/etc/datewrapper.sh'

iii). 日期

2010 年 12 月 21 日星期二 21:51:01 UTC

iv). 日期 -s “21:53:05”

2010 年 12 月 21 日星期二 21:53:05 UTC

v). 我检查了 /tmp/log/user.log。它显示消息

12 月 21 日 21:53:05 localhost root:设置新日期

因此结果是,每当用户发出date命令时,我的脚本就会被执行,并且每当他发出带有选项的命令时-s,它就会登录到/tmp/log/user.log

相关内容