【问题标题】:Passing a variable into bash command using python [duplicate]使用python将变量传递给bash命令[重复]
【发布时间】:2014-10-06 05:38:56
【问题描述】:

我正在创建一个小脚本,我想使用 python 编程语言将一个变量传递给 bash 命令,例如:

number = raw_input("digit: ")

然后我想将 number 变量放入 bash 命令中,例如:

ssh 'foo%s.bar'(number) <- where the %s is located id like it be replaced with the input

最后我想在 python 脚本中的 bash 命令中运行它:

ssh foo45.bar

我怎样才能做到这一点?

【问题讨论】:

    标签: python linux bash shell automation


    【解决方案1】:
    import subprocess
    number = raw_input("digit: ")
    subprocess.call(('ssh', 'foo{}.bar'.format(number)))
    

    如需阅读,请尝试string formatting 和subprocess 的python 文档。

    如果你想将上面的内容与sshpass集成,请将子进程调用替换为:

    subprocess.call(('sshpass', '-p', 'YOUR_PASSWORD', 'ssh', '-o', 'StrictHostKeyChecking=no', 'foo{}.bar'.format(number)))
    

    【讨论】:

    • 感谢您的意见。
    • @secure_20 这回答了您的问题吗?或者,您是否正在寻找其他信息?
    • 它有点回答了我的问题,但它要求我输入密码。我希望它也能自动传入@John1024
    • 该问题已在 Stackoverflow 上的其他地方提出:请参阅 Automatically Enter SSH Password With Script。
    • 感谢大家的帮助
    猜你喜欢
    • 2019-06-22
    • 2017-06-15
    • 2021-11-30
    • 2012-10-01
    • 2021-10-26
    • 2015-01-08
    • 2015-02-15
    • 2017-07-16
    • 2021-03-20
    相关资源
    最近更新 更多