首页 > 解决方案 > 如何为所有用户启用、禁用和重新加载 systemd 单元和服务?

问题描述

我正在编写一个包含 systemd 单元的软件包。安装后必须为所有用户启用其单元,删除后必须禁用它。

怎么做?

标签: systemd

解决方案


有一个讨论在用户模式下将其实现为“da​​emon-reexec”。

同时,这是有效的:

#! /bin/bash

Service="foo"


post_install () {
    if [[ "$(whoami)" == "root" ]]; then
        systemctl --user --global enable "${Service}"
        CommandForAllUsers systemctl --user start "${Service}"
    fi
}


pre_remove () {
    if [[ "$(whoami)" == "root" ]]; then
        CommandForAllUsers systemctl --user stop "${Service}"
        systemctl --user --global disable "${Service}"
    fi
}


post_remove () {
    if [[ "$(whoami)" == "root" ]]; then
        CommandForAllUsers systemctl --user daemon-reload
    fi
}


CommandAsUser () {
    local user="${1}"
    local command="${*:2}"

    local userId="$(id --user "${user}")"
    local bus="unix:path=/run/user/${userId}/bus"
    local sudoAsUser="sudo -u ${user} DBUS_SESSION_BUS_ADDRESS=${bus}"
    
    ${sudoAsUser} ${command}
}


CommandForAllUsers () {
    local command="${*}"
    local users; readarray -t users <<< "$(loginctl --no-legend list-users | awk '{print $2;}')"
    
    for user in "${users[@]}"; do
        CommandAsUser "${user}" "${command}"
    done
}

推荐阅读