* 未在 subprocess.Popen 中扩展(安全隐患)

* not expanded in subprocess.Popen (security implications)

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

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

这不起作用,因为 * 不会 glob

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

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

这个有效

import os
import shutil

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

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

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

Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).

If recursive is true, the pattern ** will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.

(taken from the docs)

在你的情况下它可能是这样的:

import shutil
import glob

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