0

I have a php script that will collection data and write log into a file, the directory belongs to an user called 'ingestion' and a group called 'ingestion'. I was using the command

sudo -u ingestion php [script] &>> /var/log/FOLDER/adapter.log

The owner and group of FOLDER is ingestion. However, the created adapter.log still belongs to root user and root group, how is this possible?

KevinZhou
  • 447
  • 4
  • 10
  • 2
    https://unix.stackexchange.com/questions/4830/how-do-i-use-redirection-with-sudo , https://stackoverflow.com/a/84899/635608 - the redirection is done by the shell before it starts the program (sudo in this case) – Mat Mar 02 '20 at 16:46
  • 1
    The shell get tha tline and process it step by step. One of the first things is to open the output file (as the real user calling), then it executes `sudo`, whose output has already been redirected, and runs the `php` process as the designated user. In other words: `sudo` is affecting the command being run, but the redirection is never seen by `sudo` but by the calling shell, who is the one that takes care of it. – Poshi Mar 02 '20 at 16:47

1 Answers1

1

Your file is created by the bash running as root, not by the process that you run via sudo as ingestion.

That's because the >> foo is part of the command line, not of the process started by sudo.

Here:

#foo.sh
echo foo: `id -u`

Then:

tmp root# sudo -u peter bash foo.sh > foo
tmp root# ls -l foo
-rw-------  1 root  staff  9 Mar  2 18:52 foo
tmp root# cat foo
foo: 501

You can see that the file is created as root but the foo.sh script is run as uid 501.

You can fix this by running e.g.:

tmp root# sudo -u peter bash -c "bash foo.sh > foo"
tmp root# ls -l foo
-rw-------  1 peter  staff  9 Mar  2 18:54 foo
tmp root# cat foo
foo: 501

In your case, of course, replace "..." with your php command.

petre
  • 1,485
  • 14
  • 24
  • You mean replace "bash foo.sh" with my php command, right? Thanks for you answer! – KevinZhou Mar 02 '20 at 17:01
  • One more question, i was trying something like ``` # sudo -u peter bash "php foo.php > foo" which give me a permission denied, do you know why this doesn't work? ``` – KevinZhou Mar 02 '20 at 17:06
  • Perhaps when you sudo'ed as root you changed directory to somewhere your unprivileged user cannot write? I suppose you didn't really use 'peter' but your own :-D – petre Mar 02 '20 at 17:09