繁体   English   中英

允许非 root 用户删除缓存

[英]Allowing a non-root user to drop cache

我正在一个系统上执行性能测试,我需要确保我正在从磁盘读取数据,并且它不仅仅是缓存(比如来自早期的测试)。 在这里读到我可以使用命令删除缓存

echo 3 | sudo tee /proc/sys/vm/drop_caches

但是,请注意,即使我的帐户是管理员帐户(登录 peter),它仍然需要我的密码。 我希望能够在不需要输入密码的情况下在批处理脚本中运行它(因为这显然是手动的)

更多的研究使我找到了 sudoers 文件。 我的计划是将上述命令放入一个名为 dropCache 的单行脚本中,并编辑 sudoers 以便我可以在不输入密码的情况下运行它。 所以我添加了这一行

ALL ALL=(ALL)NOPASSWD:/home/peter/dropCache

在我的 sudoers 文件末尾(使用 visudo)。 使用我的管理员帐户,如果我运行

sudo -l 

我得到

(ALL) NOPASSWD: /home/peter/dropCache

但是,如果我运行我的 dropCache 脚本,我仍然会被要求输入密码

./dropCache
[sudo] password for peter: 

对此的任何帮助将不胜感激。 我正在运行 Ubuntu 12.04

谢谢彼得

我在需要时做的是我编写了一个小程序,将编译文件的所有者更改为root,并设置setuid位。

这是源代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

extern void sync(void);

int main(void) {
    if (geteuid() != 0) {
        fprintf(stderr, "flush-cache: Not root\n");
        exit(EXIT_FAILURE);
    }
    printf("Flushing page cache, dentries and inodes...\n");
    // First: the traditional three sync calls. Perhaps not needed?
    // For security reasons, system("sync") is not a good idea.
    sync();
    sync();
    sync();
    FILE* f;
    f = fopen("/proc/sys/vm/drop_caches", "w");
    if (f == NULL) {
        fprintf(stderr, "flush-cache: Couldn't open /proc/sys/vm/drop_caches\n");
        exit(EXIT_FAILURE);
    }
    if (fprintf(f, "3\n") != 2) {
        fprintf(stderr, "flush-cache: Couldn't write 3 to /proc/sys/vm/drop_caches\n");
        exit(EXIT_FAILURE);
    }
    fclose(f);
    printf("Done flushing.\n");

    return 0;
}

我在 Ubuntu 21.04 上试过这个,它有效: 第 1 步:创建一个像下面这样的小脚本(假设名称是 clear_drop_cacahes.sh):#!/bin/sh

运行同步以减少脏缓存

同步

告诉操作系统清除缓存

回声 3 > /proc/sys/vm/drop_caches

第 2 步:chmod 744 clear_drop_caches.sh 第 3 步:需要与具有 sudo 权限的人一起执行此操作:sudo visudo #添加以下行(到文件末尾)ALL ALL=(ALL) NOPASSWD:/path-to-the -small-script/clear_drop_caches.sh

第 4 步:现在任何用户都可以运行如下所示的放置缓存脚本:sudo /path-to-the-small-script/clear_drop_caches.sh

我不确定这样做的安全性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM