2

Is there a command line command to disable access to all files and folders in the system from a python program? It should give an error if the program tries to access any file. For example, in the command line:

$ python filename.py <some_command>

or something similar.

It should not allow functions like open('filename.txt') in the program.

Edit : sudo allows to run programs with admin access. Can we create command like sudo which will limits access to another files and folders?

Thank you.

  • 3
    No there is no such magic argument. Basically Python needs file access to load libraries. It might be a good idea to sandbox your script with docker or a similar solution. – Klaus D. Apr 07 '16 at 13:47
  • @KlausD. Thank you very much –  Apr 07 '16 at 13:48
  • 1
    what operating system are you running on? unix and osx have chroot, which would allow you to force a program to run in a very limited (including empty) filesystem. – Bryan Oakley Apr 07 '16 at 13:56
  • @BryanOakley Ubuntu 15.10 –  Apr 07 '16 at 14:00

1 Answers1

0

From the list of command line options for python there doesn't seem to be this option (and sandboxing to prevent IO appears to not be too effective). You could make your own command arguments to gain this functionality, for example

import argparse

class blockIOError(Exception):
    pass

parser = argparse.ArgumentParser(description='Block IO operations')
parser.add_argument('-bIO','-blockIO', 
                   action='store_true',
                   help='Flag to prevent input/output (default: False)')

args = parser.parse_args()

blockIO = args.bIO

if not blockIO:
    with open('filename.txt') as f:
        print(f.read())
else:
    raise blockIOError("Error -- input/output not allowed")

The down side is you need to wrap every open, read etc in an if statement. The advantage is you can specify exactly what you want to allow. Output then would look like:

$ python 36477901.py -bIO
Traceback (most recent call last):
  File "36477901.py", line 19, in <module>
    raise blockIOError("Error -- input/output not allowed")
__main__.blockIOError: Error -- input/output not allowed
Community
  • 1
  • 1
Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • Thank you, but I have python programs from external source and I want to run them in my computer without giving programs permission to access other files and folders. Is there a way to do this? –  Apr 07 '16 at 14:29
  • 1
    The sandboxing options on the link above (http://stackoverflow.com/questions/10268193/disabling-std-and-file-i-o-in-python-sandbox-implementation), for example pypy sandbox, are very limited in what modules they allow but may work for your case. The suggestion from the failed pysandbox project seems to be to run the python code itself in an external sandbox (e.g. see https://lwn.net/Articles/574215/) – Ed Smith Apr 07 '16 at 16:11