Skip to main content
 首页 » 编程设计

python之从命令行禁用对 python 程序的文件访问

2025年04月02日12jiqing9006

是否有命令行命令禁止从 python 程序访问系统中的所有文件和文件夹?如果程序试图访问任何文件,它应该给出一个错误。例如,在命令行中:

$ python filename.py <some_command>

或类似的东西。

它不应该允许类似 open('filename.txt') 的函数在程序中。

编辑:sudo 允许以管理员权限运行程序。我们可以创建像 sudo 这样的命令来限制对其他文件和文件夹的访问吗?

谢谢。

请您参考如下方法:

从 python 的命令行选项列表中似乎没有这个选项(并且防止 IO 的沙盒似乎不是 too effective )。例如,您可以制作自己的命令参数来获得此功能

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") 

缺点是您需要在 if 语句中包装每个打开、读取等。优点是您可以准确指定要允许的内容。输出将如下所示:

$ 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