1

The question title pretty sums it up. I'm running a Python script which has the os.mkdir() function in it under sudo (because other functions need it). When I run it with sudo, the folder created has root as the owner and the only one with access rights. Any way to avoid this?

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
marlanbar
  • 167
  • 10
  • 1
    Is there any particular reason not to use `os.chown()` and `os.chmod()`? – Tripp Kinetics Jun 03 '14 at 19:18
  • I tried it (with `os.chmod(filedir, stat.S_IWOTH)`) and is not working. Permissions still being rwxr-xr-x. `os.chown()` is not a portable solution I think. – marlanbar Jun 03 '14 at 19:53
  • Why do you consider `os.chmod()` to be portable and `os.chown()` not to be? Does it work correctly if you replace `filedir` with a string literal? – Tripp Kinetics Jun 03 '14 at 19:59

2 Answers2

2

When sudo is run, the environment variables SUDO_UID and SUDO_GID are set to the uid and gid of the user running sudo. So:

uid = os.environ.get("SUDO_UID")
gid = os.environ.get("SUDO_GID")
if uid: os.chown(path, uid, gid)
Wire Segal
  • 21
  • 2
1

Create directories with the install command, which changes ownership and permissions automatically.

install -o myuser -d -o 0755 /tmp/mydir
johntellsall
  • 14,394
  • 4
  • 46
  • 40