【问题标题】:generate bash script in python by passing vars [closed]通过传递变量在python中生成bash脚本[关闭]
【发布时间】:2021-02-24 11:32:28
【问题描述】:

我正在尝试在 python 中通过从 CSV 文件传递​​变量来生成 bash 脚本。请问有人有什么想法吗?

示例: 我想从 csv 文件中传递 row[0] 和 row[1] CSV: 来源目的地 伦敦、巴黎

生成的 bash 脚本例如: “火车从“伦敦”开往“巴黎”

【问题讨论】:

  • 您尝试了什么,问题出在哪里?在 Python 中将变量插入字符串是微不足道的
  • 这不会被认为是一个 bash 脚本,只是一个普通的旧 python 脚本。
  • 欢迎堆栈溢出。确保您阅读了有关如何提问的指南。清晰是关键。共享数据以获得可重复性,以及您为自行解决问题所做的任何尝试。

标签: python bash csv


【解决方案1】:

假设我们有一个文件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)"

【讨论】:

  • 如果您在将值插入 bash 之前不使用 shlex.quote 对值进行转义,那么以 $(rm -rf ~) 为目标的 CSV 将非常危险。
  • (尽管——如果使用它,插入应该在 unquoted shell 上下文中,以确保 shlex.quote(或 Python 2 中的 pipes.quote)的引号添加被视为语法而不是数据;所以 f/e, echo "the train is going from \""{{source}}"\" to \""{{destination}}"\"")
  • @CharlesDuffy 感谢您的评论。至少这似乎使这段代码更安全。
  • 感谢您的帮助,这正是我所需要的。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 2011-11-14
相关资源
最近更新 更多