python - 使用python将变量传递给bash命令

标签 python linux bash shell automation

<分区>

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

number = raw_input("digit: ")

然后我想获取数字变量并将其放入 bash 命令中,例如:

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

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

ssh foo45.bar

我怎样才能让它工作?

最佳答案

import subprocess
number = raw_input("digit: ")
subprocess.call(('ssh', 'foo{}.bar'.format(number)))

要获得一些好的阅读,请尝试 string formatting 的 python 文档和 subprocess .

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

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

关于python - 使用python将变量传递给bash命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25276378/

相关文章:

python - Python 实现的 RSA 加密

Python错误-重定向尝试解析网页

python - 分而治之 - 最小硬币 - 将硬币作为数组返回

c++ Linux编译错误

linux shell存放路径

python - =+ Python 运算符在语法上是正确的

mysql - 如何启用对mysql使用man命令

linux + 如何停止在/var/spool/clientmqeueue 下创建文件

linux - 编辑一行,找不到就创建

json - 使用 jq 合并 2 个 JSON 对象