sudo python PermissionError [Errno 13] Permission denied

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Thu Dec 17 07:06:22 EST 2020


On 2020-12-17 at 11:17:37 +0100,
Pascal <patatetom at gmail.com> wrote:

> hi,
> 
> here, I have this simple script that tests if the /tmp/test file can be
> opened in write mode :
> 
> $ cat /tmp/append
> #!/usr/bin/python
> with open('/tmp/test', 'a'): pass
> 
> the file does not exist yet :
> 
> $ chmod +x /tmp/append
> $ ls -l /tmp/test
> ls: cannot access '/tmp/test': No such file or directory
> 
> the script is launched as a simple user :
> 
> $ /tmp/append
> $ ls -l /tmp/test
> -rw-r--r-- 1 user user 0 Dec 17 10:30 /tmp/test
> 
> everything is ok.
> now, the script fails if it is replayed as root user with the sudo command :
> 
> $ sudo /tmp/append
> [sudo] password for user:
> Traceback (most recent call last):
>   File "/tmp/append", line 2, in <module>
>     with open('/tmp/test', 'a'):
> PermissionError: [Errno 13] Permission denied: '/tmp/test'
> 
> the problem is the same if the opening mode is 'w' or if "sudo -i" or "su -"
> are used.
> 
> why can't root user under python manipulate the simple user file ?

This has to do with the idiosyncratic permissions of the /tmp directory
and not your code.  In my shell on my Linux box:

    $ rm -f /tmp/x
    $ echo x >/tmp/x
    $ echo x | sudo tee /tmp/x
    tee: /tmp/x: Permission denied
    x

    $ ls -ld /tmp
    drwxrwxrwt 13 root root 380 Dec 17 06:03 /tmp

Try your experiment in a different directory, one without the sticky bit
set.


More information about the Python-list mailing list