python permission denied writing output to file
Solution 1
The problem here sudo python myFile.py >> log.txt
is that you run sudo python myFile.py
as root, but your shell is still running as your regular user, which means >>
redirection won't work if you don't have permission to write to the log.txt
As George properly noted, you should do sudo bash -c "python myFile.py >> log.txt"
. Alternatively, if your myFile.py
doesn't require root privileges, you can do python myFile.py | sudo tee log.txt
Solution 2
Two options I can think of:
sudo bash -c "python myFile.py >> log.txt"
, orsudo chmod u+x myFile.py
, thensudo ./myFile.py >> log.txt
Related videos on Youtube
black
Updated on September 18, 2022Comments
-
black over 1 year
I want to execute a python file in
/var/www/html
:sudo python myFile.py
Which works fine.
Now, I want to write the output to
log.txt
.So, I type:
sudo python myFile.py >> log.txt
However, I get the following error:
-bash: log.txt: Permission denied
Though I changed the permissions of log.txt:
sudo chmod u+x log.txt
And
ls -l log.txt
returns:-rwxr--r-- 1 www-data www-data 0 Feb 3 16:04 log.txt
How can I fix this?
-
Admin over 7 yearsAre you running
myFile.py
with www-data? -
ridgy over 7 yearsCould it be that /var/www/html is on a network share? Try
df /var/www/html
-
George Udosen over 7 yearsTry
sudo bash -c "python myFile.py >> log.txt"
-
black over 7 years@bc2946088 Yes, I am www-data
-
-
black over 7 yearsThank you for the explanation. I assumed already such a situation, that the shell has not the rights. However, is there a possibility to change the rights to log.txt so that I can do it without sudo? I tried it (see above), but I assume that the rights were just changed for my user (group) and not for the bash, right?
-
Sergiy Kolodyazhnyy over 7 years@black The file is owned by
www-data
user and group. So, you could add yourself towww-data
usingsudo usermod -a -G www-data <USERNAME>
command (where<USERNAME>
is your actual username). Although I wouldn't recommend doing that. As far as I understand ,www-data
group is for your web server, so if your account gets compromised, attacker could have access to modifying the web server without need forsudo
.