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

标签 python file shell command-line command

是否有命令行命令禁止从 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

关于python - 从命令行禁用对 python 程序的文件访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477901/

相关文章:

python - 创建满足一个条件的多个列表 Python 3.6

html - 我在 Github 中的 CSS 文件未被 HTML 文件使用

c - 从文件中分配一个 char* 数组

python - 使用 Python Paramiko exec_command 执行时,一些 Unix 命令失败并显示 "<command> not found"

Python特定的PATH环境变量?

windows - 从 shell 脚本调用存储过程

python - 无法在模拟方法上设置 side_effect

javascript - 上传到 Google Cloud Storage 时获取 403 SignatureDoesNotMatch?

python oracle 将结果放入字典并匹配给定的列表

java - 检查文件结尾未按预期工作