Launch a temporary root process with `systemd‑run` instead of `sudo`

Run a single command as root with systemd‑run

When you just need to fire up one command as root and then drop back, sudo is the go‑to.
But if your distro already runs systemd, systemd‑run can be a leaner, more isolated way to do it—especially for short‑lived tasks.

What systemd‑run actually does

systemd‑run spawns a transient unit (either a scope or a service) that inherits the caller’s privileges and then elevates them to root when you add --user or --scope with --user.
Unlike sudo, the unit vanishes as soon as the command finishes, and you can sprinkle a handful of systemd properties on it to tighten the environment.

sudo systemd-run --user \
    --property=PrivateTmp=true \
    --property=NoNewPrivileges=yes \
    --property=ProtectSystem=full \
    --property=ProtectHome=yes \
    --property=MemoryLimit=256M \
    --property=CPUQuota=50% \
    --property=ExecStart=/usr/bin/apt-get update

That line runs apt‑get update as root, but with a 256 MiB memory cap, half a CPU share, a private /tmp, and no chance to spawn new privileges.
When the command exits, the transient unit disappears automatically.

Isolation properties that give you a security edge

PropertyWhat it doesTypical use case
PrivateTmp=trueGives the unit its own /tmp and /var/tmp.Prevents leaking sensitive data to other processes.
NoNewPrivileges=yesDisallows setuid/setgid binaries from gaining new privileges.Stops privilege escalation inside the unit.
ProtectSystem=fullMounts the root filesystem read‑only, except for /var.Protects the system from accidental writes.
ProtectHome=yesMounts home directories read‑only.Keeps user data safe.
PrivateDevices=yesIsolates device nodes.Useful when running hardware‑intensive tools.
RestrictAddressFamilies=AF_INET,AF_INET6Limits network sockets.Prevents outbound connections if not needed.
MemoryLimit= / CPUQuota=Caps resources.Avoids runaway processes.

These properties are optional; pick the ones that make sense for your task.
I’ve seen this go wrong when people forget to set NoNewPrivileges, letting a malicious binary sneak in a new capability. The real trick is to keep the unit as minimal as possible—no more than you need to run that single command.

In practice, just add the properties you care about. Don’t bother with a full‑blown service file for a one‑shot job. systemd‑run is a handy tool to keep the system tidy and the attack surface small.


See also