2

This is my script

#!/usr/bin/python

import os

print "hello world from python"
os.system("echo 'hello world from bash'")
os.system("umask 055")
os.system("ls -alh > test")

If I run this code the permissions of file test are not set as 722 but as 600. What could be the reason?

the Umask of my shell is 0077.

2

When you run umask with system it runs in a shell: umask changes the mask of that shell, but the shell then immediately terminates and the change is lost.

To change the umask of your Python process, use os.umask(), which will:

Set the current numeric umask and return the previous umask.

That way the change will be made to your running program, rather than another program that immediately dies afterwards.

  • This still dosent change the umask of my shell. I want to change umask of my shell – Shaels Jul 17 '14 at 5:19
  • 1
    If you want to change the umask of the shell you're running things from, use umask directly in it. If you want to change the umask of your Python program and any programs that you start from it, do this. – Michael Homer Jul 17 '14 at 5:28
  • I basically want to change umask of my shell from a script. I thought of doing hardening of the system by running a script. Is there any way to do that in python? – Shaels Jul 17 '14 at 5:37
  • Inherently you can't do that. If you really really want to, you could spawn a login shell after you changed the umask in Python: os.system("bash -i"). It has no security value, though. – Michael Homer Jul 17 '14 at 5:41
2

This is perfectly normal behaviour, but probably not what you intend.

The umask 055 settings are there for the duration of the os.system call, so they never change the settings for the Python script, and certainly not for the command called in the next os.system() call.

What you should do is something like:

import os

old_mask = os.umask(055)
os.system("ls -alh > test")
os.umask(old_mask)
0

If you want an underlying shell command to run with certain permissions it would be possible to accomplish this by chaining the commands in a single system call.

os.system("umask 055")
os.system("ls -alh > test")

Becomes:

os.system("umask 055; ls -alh > test")

or, if you only want to run the second command if the previous exited successfully:

os.system("umask 055 && ls -alh > test")

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.