echo into a file won't work with sudo -u

Hello fellow HTBlers,

I need help understanding something. There is a User Folder somewhere with a py-File in it. I’m in some kind of a bash where it’s not possible to use nano or vi. Now I want to edit the content of this py-File and my solution would be sudo -u USERNAME echo “something” /USERDIR/something.py. But nothings happens.

I can however do ls -ls with sudo -u, I can can cat the content of the File with sudo -u and create a new File with touch. However, echo into the new File won’t work either. Can someone explain to me why? Is there another way to edit a File without starting an editor? I only know echo should do this.

Thank you

You need to understand executable boundaries in your shell. Sudo will execute a command with elevated privileges, but the results of that command are still running in your session scope.

A better way to show it is this example. The text in the s is executed by sudo, the rest is executed by your current bash session:

sudo -u someuser [command arg1 arg2] > output.txt

The “>” is bash redirection and is handled by your shell. Most commands aren’t even aware this is happening, the ones that do are usually tty aware and can see the stdout isn’t a tty device.

If you want to edit a file without an editor through sudo, look into sed, or dd.

Replace a config option:
sudo sed -i ‘s/^setting = .*/setting = newvalue/’ configfile

Replace the entire contents of a file:
cat replacement.file | sudo dd of=target.file

Both of these handle the file access within the scope of the sudo session, rather than using redirects from your current shell.

That’s a great answer, cdf123. CaptnCrash, are you only able to edit it remotely?

first do
test@hostname$ sudo -u SOMEUSER bash

after dat u got shell of dat user dan try to echo something …

SOMEUSER@hostname$ echo “YOUR_CONTENT” > filename.py

thank you all very much!