【问题标题】:* not expanded in subprocess.Popen (security implications)* 未在 subprocess.Popen 中扩展(安全隐患)
【发布时间】:2018-08-08 09:28:54
【问题描述】:

这可行,但 shell 注入存在安全风险

p = subprocess.Popen(['mv ./*.pdf ./target.pdf'], shell=True)

这不起作用,因为 * 不会全局化

p = subprocess.Popen(['mv', './*.pdf', './target.pdf'])

我在看一个目录。如何在不影响安全性的情况下将到达的 pdf 重命名为 target.pdf?

【问题讨论】:

  • 为什么不先在你的 python 脚本中使用glob 来查找文件名。
  • 既然可以使用shutil.move(),为什么还要使用subprocess
  • @FlyingTeller 我正在使用看门狗将任何到达的 pdf 文件重命名为 target.pdf,该文件由 subprocess.Popen 传递给 tika-parser 那么我将如何首先 glob?
  • @nauer 我是初学者。谢谢你的提示。我将发布我的笨拙的解决方案,我确信可以做得更好......
  • @user1613312 在您发布的答案中使用 listdir 的方式相同。只需sources = glob.glob('*.pdf')

标签: python shell subprocess code-injection


【解决方案1】:

您可以使用glob 模块中的glob 命令来获取类似于shell 的路径扩展:

glob.glob(pathname, *, recursive=False)

返回与路径名匹配的可能为空的路径名列表,该列表必须是包含路径规范的字符串。路径名可以是绝对的(如/usr/src/Python-1.5/Makefile)或相对的(如../../Tools/*/*.gif),并且可以包含shell 样式的通配符。结果中包含损坏的符号链接(如在 shell 中)。

如果recursive 为真,则模式** 将匹配任何文件以及零个或多个目录和子目录。如果模式后跟 os.sep,则只有目录和子目录匹配。

(取自docs

在您的情况下,它可能如下所示:

import shutil
import glob

sources = glob.glob('*.pdf')
destination = "target.pdf"
for file in sources:
    shutil.move(file, destination)

【讨论】:

  • source = glob.glob('*.pdf') destination = "target.pdf" for file in source: shutil.move(file,destination)
【解决方案2】:

这行得通

import os
import shutil

source = os.listdir(os.curdir)
destination = "target.pdf"
for files in source:
    if files.endswith(".pdf"):
        shutil.move(files,destination)

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 2010-09-07
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2017-10-24
    • 2012-07-13
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多