Warm tip: This article is reproduced from serverfault.com, please click

redirecting output using sudo

发布于 2021-01-13 23:10:37

I want to run a command as another user using sudo, and redirecting the output of that command as that user. Example, if I run:

touch some-file

under user simon, some-file will be owned by user simon. If I run:

sudo -u ernesto touch some-file

then some-file is owned by user ernesto, as I am specifying that I want to run the touch command as ernesto. Finally, if I run:

sudo -u ernesto ls /some-folder/ > some-file

some-file is again owned by user simon, as the > operator is redirecting the output of the whole command before >, to some-file (which is in fact being ran by user simon). I need to grab the output of listing a directory as ernesto but using sudo, as the directory that I want to list, is owned by ernesto, and I can't list the directory using with simon.

It has to be using sudo, as the user ernesto allows me to run sudo commands without password.

I tried

sudo -u ernesto $(ls /some-folder/ > some-file)
sudo -u ernesto `ls /some-folder/ > some-file`
sudo -u ernesto 'ls /some-folder/ > some-file'
sudo -u ernesto eval(ls /some-folder/ > some-file)
sudo -u ernesto exec(ls /some-folder/ > some-file)

hoping for something of this to work, but still no luck.

Questioner
Simon Ernesto Cardenas Zarate
Viewed
22
Ginnungagap 2019-01-24 15:07:02

You can use tee through sudo to write to a file as another user.

In your use case of writing a directory listing, it becomes a simple

sudo -u ernesto ls some-directory | sudo -u ernesto tee some-file