How to Use Os.Umask() in Python

Python os.open() can not set umask to 777 (755 max)

You're not setting umask, you're setting the file mode bits, which are masked by the umask. Per the documentation:

Open the file file and set various flags according to flags and
possibly its mode according to mode. The default mode is 0777 (octal),
and the current umask value is first masked out. ...

Your umask value appears to be 0022, thus masking out group and other user write permissions.

This

os.fchmod(f, 0777)

explicitly sets the file permissions to 0777 despite the umask value.

Reading umask (thread-safe)

if your system has Umask field in /proc/[pid]/status, you could read from on it:

import os

def getumask():
pid = os.getpid()
with open(f'/proc/{pid}/status') as f:
for l in f:
if l.startswith('Umask'):
return int(l.split()[1], base=8)
return None

tested under CentOS 7.5, Debian 9.6.

or, you could add a thread lock :)

Why is the argument of os.umask() inverted? (umask 0o000 makes chmod 0o777)

There is no real inconsistency, as the relation between umask and chmod can purely be written down with equations. Apparently, umask sets the opposite of chmod, it was created like this back in the old days.

Example: 022 (the default usual umask) creates 755. It works like this:

  • 7 - 0 = 7 becomes the first byte
  • 7 - 2 = 5 becomes the second and third bytes

Using this example, umask 777 creates a file with chmod 000, umask 112 will be equal to chmod 664. As far as I know, this happened because the umask command was originally created to indicate what permission bits the file will NOT have after it's created (hence the invertion).

While it could be annoying, it's really not hard to get used to it. Just think how you would chmod your files, and subtract the byte you want from 7, and you will get the umask value. Or, when you are at the IDE, writing your code, don't use umask, but rather create the file (with the default umask of course) and then use, in Python, os.chmod() instead.

How can I set the umask of a process I am spawning?

Since the preexec_fn argument seems to work for you, you can use it to call os.umask() as well:

def initchildproc():
os.setpgrp()
os.umask(400)

subprocess.Popen(cmd, shell=False, preexec_fn=initchildproc, ...)

Write file with specific permissions in Python

What's the problem? file.close() will close the file even though it was open with os.open().

with os.fdopen(os.open('/path/to/file', os.O_WRONLY | os.O_CREAT, 0o600), 'w') as handle:
handle.write(...)


Related Topics



Leave a reply



Submit