I am trying to write bytes to a file. Generally, one could simply do:
...
fb = file.read() # this contains the bytes to copy
with open("/tmp/", "wb") as out:
out.write(fb)
It works perfectly, but I am trying to make it work with subprocess. Why? Because I need the output file to be created under the ownership of a different user - say userA. And the only way possible I am seeing is user impersonation. An example below:
# runs as root
import subprocess
def run(cmd, **kwargs):
popen = subprocess.Popen(
cmd.split(),
stdout=kwargs.pop("stdout", subprocess.PIPE),
stderr=kwargs.pop("stderr", subprocess.PIPE),
user=kwargs.get("user")
)
popen.communicate()
dst = "/data/userA" # special (network) location that only userA can access (not even root)
byte_data = file.read() # this contains the bytes to copy
user = "userA"
with open(dst, mode="wb") as out_f:
cmd = f"echo -n {byte_data}"
run(cmd=cmd, user=user, stdout=out_f)
If I send a txt file, my content is b"text content".
My limitations:
- File can be of any format: text, images, video, etc. therefore I can't decode it.
- I can't create the file as
rootandchownit touserAsince not even root can access that location.