python permission denied writing output to file

24,364

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:

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

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

Share:
24,364

Related videos on Youtube

black
Author by

black

Updated on September 18, 2022

Comments

  • black
    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
      Admin over 7 years
      Are you running myFile.py with www-data?
    • ridgy
      ridgy over 7 years
      Could it be that /var/www/html is on a network share? Try df /var/www/html
    • George Udosen
      George Udosen over 7 years
      Try sudo bash -c "python myFile.py >> log.txt"
    • black
      black over 7 years
      @bc2946088 Yes, I am www-data
  • black
    black over 7 years
    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?
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy over 7 years
    @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.