1

I am going to read a file which needs root privilege and I have to save it somewhere with another user or group, for example reading dmesg which needs root and save it some other place with permission 770 for user/group: test/test. the problem here that I can not save it as root, is SElinux policy which gives me error.So I need to change the process privilage while I am saving the file.

any suggestion?

2
  • Will your script be running as root? Commented Sep 5, 2022 at 8:24
  • @roaima, yes, ,It runs as root Commented Sep 5, 2022 at 8:46

2 Answers 2

2

Your script is running as root. So there's nothing to stop you using sudo to run as any user. If you can't write a file as root but you can as this other user, that's one option:

target=/path/to/target/file
dmesg | sudo -u test tee "$target" >/dev/null
chmod 770 "$target"

If you prefer to use su instead of sudo you can use this variant

target=/path/to/target/file
dmesg | su test -c "tee '$target' >/dev/null'
chmod 770 "$target"
5
  • 1
    I wonder if install could be used too?
    – Kusalananda
    Commented Sep 5, 2022 at 11:24
  • 1
    @Kusalananda I don't think so - strace shows the file being written and then the ownership applied Commented Sep 5, 2022 at 11:54
  • Good call. Thanks for looking into that.
    – Kusalananda
    Commented Sep 5, 2022 at 12:07
  • Thank you, it works for me, the only change I give was to use su instead of sudo and give the complete address of all command. for example dmesg and su Commented Sep 5, 2022 at 13:06
  • @AhmadBanshee both dmesg and su are in the standard /bin directory so you shouldn't have needed to provide full paths. Have you perhaps changed the $PATH variable by mistake? Commented Sep 5, 2022 at 16:50
1

With zsh, you can do (as root):

zmodload zsh/system
umask 0
() {local EGID=123 EUID=456; sysopen -wu3 -m770 -o excl file}

To create and open the file as euid 456 and egid 123 with 0770 permissions.

$ ls -nd file
-rwxrwx--- 1 456 123 0 Sep  5 17:05 file

And then run: dmesg >&3 to fill it up.

(note that the order is important, you can't change the egid once your euid is no longer 0).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .