0

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?

  • Are you running myFile.py with www-data? – user508889 Feb 3 '17 at 18:32
  • Could it be that /var/www/html is on a network share? Try df /var/www/html – ridgy Feb 3 '17 at 18:35
  • 1
    Try sudo bash -c "python myFile.py >> log.txt" – George Udosen Feb 3 '17 at 18:36
  • @bc2946088 Yes, I am www-data – black Feb 3 '17 at 18:45
2

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

  • Thank 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? – black Feb 3 '17 at 19:04
  • @black The file is owned by www-data user and group. So, you could add yourself to www-data using sudo 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 for sudo. – Sergiy Kolodyazhnyy Feb 3 '17 at 19:24
1

Two options I can think of:

  1. sudo bash -c "python myFile.py >> log.txt", or

  2. sudo chmod u+x myFile.py, then sudo ./myFile.py >> log.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.