brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: runuser runs a command as another Linux user without a password or sudo rule

Linux
~/tips/tip-linux-runuser-as-service-account

runuser -u www-data -- php /var/www/app/occ status

Run a command as a service account from a root script, without su or sudo prompts.

In a root script you often need to run one command as a service account, such as www-data or postgres. su wants a login shell and sudo needs rules. runuser is made for exactly this case.

runuser -u www-data -- php /var/www/app/occ status

It runs the command as that user, with that user’s ID and groups, and returns its exit code. Everything after -- is the command, so options for the command cannot be mistaken for options of runuser. It never asks for a password, because it only works for root in the first place.

When the command needs the user’s own environment, such as HOME and their login profile, use the login form:

runuser -l postgres -c 'pg_dumpall > /var/backups/all.sql'

It also works for accounts with nologin as their shell, because -u runs the command directly instead of going through a shell. That is the main reason I’d use it for service accounts: su would fail on them.

Since it is root only, it is not a tool for regular users. In the -l form the redirection inside the quotes runs as the target user, so that user needs permission to write the output file. And unlike sudo, runuser does not log which command ran as whom, so in scripts that matter for an audit, sudo with a specific rule may be the better choice.

Further reading: runuser(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link