给定一个路径,无需root即可获取UUID

问题描述 投票:0回答:1

我的问题很简单,给定一个路径\挂载点:是否可以获取其所属设备的UUID,而不需要C中的root访问权限?如果是这样,您将如何解决这个问题? (效率很重要)

c path root uuid
1个回答
0
投票

只要您的系统在

/dev/disk/by-uuid
中有符号链接,您就可以根据其UUID来匹配设备,而无需sudo。该目录包含基于 UUID 的块设备链接,这意味着您无需直接访问设备即可找到 UUID。

示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>


#define UUID_PATH_PREFIX "/dev/disk/by-uuid/"
#define UUID_PATH_LENGTH (18 + 36 + 1)  // Length of prefix + UUID + null terminator


int get_uuid_from(const char *mountpoint, char *uuid_buf, size_t buf_size) {
    struct dirent *entry;
    DIR *dp = opendir(UUID_PATH_PREFIX);
    if (dp == NULL) {
        perror("opendir failed");
        return -1;
    }

    struct stat mount_stat, link_stat;
    if (stat(mountpoint, &mount_stat) != 0) {
        perror("stat on mountpoint failed");
        closedir(dp);
        return -1;
    }

    char path[UUID_PATH_LENGTH];
    while ((entry = readdir(dp)) != NULL) {
        snprintf(path, sizeof(path), "%s%s", UUID_PATH_PREFIX, entry->d_name);

        if (stat(path, &link_stat) == 0 && link_stat.st_rdev == mount_stat.st_rdev) {
            strncpy(uuid_buf, entry->d_name, buf_size - 1);
            uuid_buf[buf_size - 1] = '\0';  // Ensure null termination
            closedir(dp);
            return 0;
        }
    }

    closedir(dp);
    return -1;
}


int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <mountpoint>\n", argv[0]);
        return EXIT_FAILURE;
    }

    char uuid[37];  // UUID is 36 chars + null terminator
    if (get_uuid_from(argv[1], uuid, sizeof(uuid)) != 0) {
        fprintf(stderr, "Failed to retrieve UUID for %s\n", argv[1]);
        return EXIT_FAILURE;
    }

    printf("UUID for %s: %s\n", argv[1], uuid);
    return EXIT_SUCCESS;
}
gcc -o get_uuid_test get_uuid_test.c
./get_uuid_test /dev/mapper/root

参考文献

免责声明

我必须承认,这是我主要从 chat-gpt 得到的答案,由我评估和完善。虽然我也发现它已经被回答了here,但最终我决定花时间并在新帖子中通过示例提供完整的答案。

© www.soinside.com 2019 - 2024. All rights reserved.