【问题标题】:Monitor chattr changes监控 chattr 变化
【发布时间】:2020-02-19 02:55:42
【问题描述】:

当有人通过命令行更改目录或文件属性时,我想在 C 程序中得到通知:chattr。

例如:

mkdir -p /tmp/test
sudo chattr +i /tmp/test

我想编写一个程序来检测 /tmp/test 目录何时变得不可变并做出反应。 我找到了 inotify,但它只会检测 chmod、setxattr... 更改,但不会检测 chattr。

【问题讨论】:

标签: c linux


【解决方案1】:
struct ev_loop* loop = nullptr;
int fd = 0;
void
sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
  else if (signo == SIGTERM)
    printf("received SIGTERM\n");
  else if (signo == SIGBUS)
    printf("received SIGBUS\n");
  else if (signo == SIGABRT)
    printf("received SIGABRT\n");
  if (loop != nullptr) {
    std::cout << "Stopping event loop" << std::endl;
    ev_break(EV_A_ EVBREAK_ONE);
  }
}
void
monitoring(struct ev_loop* loop, struct ev_io* io, int revents)
{
  struct audit_reply reply;

  audit_get_reply(fd, &reply, GET_REPLY_NONBLOCKING, 0);

  if (reply.type != AUDIT_EOE && reply.type != AUDIT_PROCTITLE &&
      reply.type != AUDIT_PATH) {
    char* buf = new char[MAX_AUDIT_MESSAGE_LENGTH];

    snprintf(buf,
             MAX_AUDIT_MESSAGE_LENGTH,
             "Type=%s Message=%.*s",
             audit_msg_type_to_name(reply.type),
             reply.len,
             reply.message);

    printf("EVENT: %s\n", buf);
  }
}

int
main()
{
  std::cout << "Starting up..." << std::endl;

  if (signal(SIGINT, sig_handler) == SIG_ERR) {
    printf("can't catch SIGINT\n");
  }
  if (signal(SIGTERM, sig_handler) == SIG_ERR) {
    printf("can't catch SIGTERM\n");
  }
  if (signal(SIGBUS, sig_handler) == SIG_ERR) {
    printf("can't catch SIGBUS\n");
  }
  if (signal(SIGABRT, sig_handler) == SIG_ERR) {
    printf("can't catch SIGABRT\n");
  }

  struct ev_io monitor;
  fd = audit_open();

  audit_set_pid(fd, getpid(), WAIT_YES);
  struct audit_rule_data* rule = new audit_rule_data();

  std::cout << "Add watch dir..." << std::endl;
  audit_add_watch_dir(AUDIT_DIR, &rule, "test");

  // setting rule.
  audit_add_rule_data(fd, rule, AUDIT_FILTER_EXIT, AUDIT_ALWAYS);

  loop = EV_DEFAULT;

  ev_io_init(&monitor, monitoring, fd, EV_READ);

  std::cout << "Enable audit..." << std::endl;
  audit_set_enabled(fd, 1);
  std::cout << "Start io monitor..." << std::endl;
  ev_io_start(loop, &monitor);
  std::cout << "Start event loop..." << std::endl;
  // now wait for events to arrive
  ev_run(loop, 0);
  std::cout << "Closing audit..." << std::endl;
  audit_close(fd);
  delete rule;

  std::cout << "Bye" << std::endl;
  return 0;
}

【讨论】:

    猜你喜欢
    • 2010-12-14
    • 1970-01-01
    • 2010-10-05
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2010-10-13
    • 2022-01-04
    相关资源
    最近更新 更多