在systemd用户服务中设置niceness值

Lib*_*lor 9 linux xorg user nice systemd

我想以 -20 作为非 root 启动 xcape。然而,设置一个好的值 -20 需要 root 权限。所以我想知道这是否可能。我还尝试创建系统服务和设置User=myuser,但 xcape 需要 xorg,DISPLAY因此XAUTHORITY

到目前为止我得到了什么:

[Unit]
Description=xcape: esc on caps lock
PartOf=graphical-session.target

[Service]
Type=simple
Nice=-20
ExecStart=/usr/bin/xcape -t 180 -e 'Caps_Lock=Escape'

[Install]
WantedBy=default.target
Run Code Online (Sandbox Code Playgroud)

Lib*_*lor 5

我最终想出了一个使用 sudo 1的解决方法,因为 systemd 不支持开箱即用。

1)在sudoers文件中添加命令

首先将以下行添加到末尾/etc/sudoers(替换myusername为您的用户名,mycommand并根据需要执行命令并调整好值):

myusername ALL=(root) NOPASSWD: /usr/bin/nice -n -20 sudo -u myusername mycommand
Run Code Online (Sandbox Code Playgroud)

说明:
允许用户以 rootmyusername身份执行命令sudo /usr/bin/nice -n -20 sudo -u myusername mycommand而无需输入密码。由于sudo nice -n -20 mycommand将以mycommandroot 身份执行,因此我们将其添加sudo -u myusername到命令前面,这种方式mycommandmyusername. 这是遵守最小特权原则的安全措施。

2)在服务脚本中使用sudo执行命令

现在我们可以执行这个特定的命令而无需输入密码:

[Service]
ExecStart=sudo /usr/bin/nice -n -20 sudo -u myusername mycommand
Run Code Online (Sandbox Code Playgroud)

示例:xcape

/etc/sudoers

myusername ALL=(root) NOPASSWD: /usr/bin/nice -n -20 sudo -u myusername xcape -t 180 -e Caps_Lock=Escape
Run Code Online (Sandbox Code Playgroud)

〜/.config/systemd/user/xcape.service

[Unit]
Description=xcape: esc on caps lock
PartOf=graphical-session.target

[Service]
Type=forking
ExecStart=sudo /usr/bin/nice -n -20 sudo -u myusername mycommand

[Install]
WantedBy=default.target
Run Code Online (Sandbox Code Playgroud)

启动服务:systemdctl --user start xcape


1如果 sudo 不可用,还可以编写一个帮助程序可执行文件并使用 setuid 位。