假设我们有一个文件routes.csv,其中包含路线列表:
source,destination
London,Paris
Paris,Amsterdam
Amsterdam,London
还有一个 bash 脚本模板route.sh.tpl:
#!/bin/bash
echo "the train is going from \""{{source}}"\" to \""{{destination}}"\""
下面是一个简短的示例,它使用 csv 文件中的数据实例化一个模板,然后执行生成的文件。
import csv
import subprocess
import shlex
import jinja2
CSV_FILE='routes.csv'
BASH_FILE='routes.sh'
TPL_FILE='routes.sh.tpl'
with open(CSV_FILE, 'r') as csv_file:
template = jinja2.Template(open(TPL_FILE).read())
reader = csv.DictReader(csv_file)
for row in reader:
for key,value in row.items():
row[key] = shlex.quote(value) # prevent unsafe inputs
with open(BASH_FILE, 'w') as bash_file:
bash_file.write(template.render(**row))
subprocess.call(['/bin/bash', BASH_FILE])
更新来自 Charles Duffy 的评论。将从外部文件读取的数据传递给 shell 可能容易被滥用。使用 Python 3 shlex 模块,可以使用 shlex.quote 使这个示例更安全。
考虑恶意输入
source,destination
London,Paris
Paris,Amsterdam
Amsterdam,$(rm -f testfile; echo London)
如果输出看起来与原始输入一样,则系统已受到威胁。此输入的正确输出应如下所示。
the train is going from "London" to "Paris"
the train is going from "Paris" to "Amsterdam"
the train is going from "Amsterdam" to "$(rm -f testfile; echo London)"