操作不允许

3 投票
1 回答
3658 浏览
提问于 2025-04-16 09:59

我想在Python脚本中运行一些命令。

import fcntl

KDSETLED = 0x4B32
SCR_LED  = 0x01

console_fd = os.open('/dev/console', os.O_NOCTTY)
fcntl.ioctl(console_fd, KDSETLED, SCR_LED)

我已经为/dev/console设置了a+rw的权限,但当我以普通用户身份运行脚本时:

fcntl.ioctl(console_fd, KDSETLED, SCR_LED) IOError: [Errno 1] 操作 不被允许

如果我需要以普通用户身份运行这个脚本,我该怎么办?

1 个回答

4

我觉得你需要让你的脚本执行时具备 CAP_SYS_TTY_CONFIG 权限。或者,如果你是在控制台上运行的话,使用你的控制终端(比如 /dev/tty1)而不是 /dev/console 可能也能解决问题。

负责这个限制的内核代码似乎在 drivers/tty/vt/vt_ioctl.c 文件里:

/*
 * To have permissions to do most of the vt ioctls, we either have
 * to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
 */
perm = 0;
if (current->signal->tty == tty || capable(CAP_SYS_TTY_CONFIG))
    perm = 1;
⋮
case KDSETLED:
    if (!perm)
        goto eperm;
    setledstate(kbd, arg);
    break;

所以,看起来这就是你可以选择的两个方案。

撰写回答