Search code examples
linuxbashsudodbuspolkit

How to drop privileges in bash script between pipes?


dbus-monitor --system --profile interface=org.freedesktop.login1.Session,type=signal,member={Lock,Unlock} |
  egrep --line-buffered -o 'Lock|Unlock' |
  while read SIGNAL; do
    case "${SIGNAL}" in
      Lock)
        for i in "$(systemd-path user-shared)/watchlock/lock.d/"*; do
          "${i}"
        done
        ;;
      Unlock)
        for i in "$(systemd-path user-shared)/watchlock/unlock.d/"*; do
          "${i}"
        done
        ;;
    esac
  done

I've made this script and I want to execute it as a regular user but dbus-monitor only works as root. Is there a way to execute dbus-monitor as root and the rest of the pipes as a regular user? Adding sudo before dbus-monitor is not an option as it is just a workaround, I could intend to execute the script as root and it would escalate privileges once again for no reason. I would also want to make use of polkit, pkexec for example. Thanks!


Solution

  • Just like this:

    cmd_a | sudo -u "${USER}" cmd_b
    

    If the script is started as root, cmd_a will run as root and cmd_b will run as $USER.