3

I'm writing a script that will copy directories from a drive that I have full access to. I'm wondering if it is possible to set a parameter in the script to prevent the rest of script from modifying/deleting directories that it will be processing.

Something like:

import os 
import shutils

os.preventFromModify() 
shutil.rmtree("path") # should not be possible
Nam G VU
  • 33,193
  • 69
  • 233
  • 372
Adam Stepniak
  • 815
  • 6
  • 21
  • Are you trying to prevent bugs from overwriting important files or is part of the script not code you trust? – Blender Apr 19 '18 at 20:44
  • 3
    It sounds like you want OS-level protection. I imagine that you can't prevent your code from just calling into exposed APIs that modify files. You probably just want to change permissions on those files. (which you can do by the way with [`os.chmod`](https://stackoverflow.com/questions/16249440/changing-file-permission-in-python)) – pushkin Apr 19 '18 at 20:47
  • Not sure, but maybe you could also change the user executing the script, so it has fewer rights? – tobias_k Apr 19 '18 at 20:48
  • Regarding my previous point though, the code later could just change the permissions back... Could you expand on why you're trying to do this? – pushkin Apr 19 '18 at 20:56
  • You could take the extreme step of re-mounting the file system(s) as read-only. Short of that, I don't think there is anything you can do as general as what you are asking. – chepner Apr 19 '18 at 21:05
  • One can always have a process-local mount table with the read-only flag set (on an OS that supports such a thing, but that includes modern Linux). Tools like SELinux provide even more detailed / fine-grained per-process permissions. – Charles Duffy Apr 19 '18 at 21:11
  • Similarly, on Linux, the `seccomp` framework can be used to lock down which syscalls a process can make -- so one could disable `unlink()` altogether. Would of course need to prevent equivalents such as `truncate()`, `open()`, etc. as well -- the need to lock down `open()` means starting up the interpreter and loading libraries/etc. you need *before* putting the filter in place for that process. – Charles Duffy Apr 19 '18 at 21:13
  • Are you trying to protect against malicious use, or just sloppy coding? – Bryan Oakley Apr 19 '18 at 21:16

1 Answers1

0

Quote this comment as the answer for you.

It sounds like you want OS-level protection. I imagine that you can't prevent your code from just calling into exposed APIs that modify files. You probably just want to change permissions on those files. (which you can do by the way with os.chmod) – pushkin Apr 19 '18 at 20:47

Nam G VU
  • 33,193
  • 69
  • 233
  • 372