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
| Property | What it does | Typical use case |
|---|---|---|
PrivateTmp=true | Gives the unit its own /tmp and /var/tmp. | Prevents leaking sensitive data to other processes. |
NoNewPrivileges=yes | Disallows setuid/setgid binaries from gaining new privileges. | Stops privilege escalation inside the unit. |
ProtectSystem=full | Mounts the root filesystem read‑only, except for /var. | Protects the system from accidental writes. |
ProtectHome=yes | Mounts home directories read‑only. | Keeps user data safe. |
PrivateDevices=yes | Isolates device nodes. | Useful when running hardware‑intensive tools. |
RestrictAddressFamilies=AF_INET,AF_INET6 | Limits 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
- Turn tmux into a systemd service so your long‑running processes keep running after logout
- How to pull a single file from a Borg backup without unpacking the entire archive
- Summarizing /var/log/syslog Errors into JSON with jq for Grafana Dashboards
- Why ssh keeps asking for a password after adding a key and how to correct the PubkeyAuthentication setting
- When systemd‑resolved overrides /etc/hosts: a quick fix