python - 使用 python 变量执行 shell 命令

标签 python subprocess

我在 bash 上有脚本,我在其中为用户生成了用户名、密码和 ssh key 。 用于创建 ssh-key 的部分:

su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"

如何在 Python 中使用 os.system 做同样的事情?我试过这个:

os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)

我也试过:

os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')

当然也不行。

最佳答案

使用 os 包格式化您的指令;例如:

import os

user = 'joe'
ssh_dir = "/home/{}/.ssh/id_rsa".format(user)
os.system("ssh-keygen -f {} -t rsa -b 4096 -N ''".format(ssh_dir))

关于python - 使用 python 变量执行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47308367/

相关文章:

python - 使用 vscode 新调试器调试 python 版本 < 3.5

python - 在 python 中终止子进程

java - 使用相对路径运行 Java 主类? (Python)

python - Unresolved reference 'build' - YouTube Python API

python - PyInstaller 的权限错误(以管理员身份运行)

python - 填充 groupby 对象序列,Pandas

python - PyQt4 python 中的 "RuntimeError: maximum recursion depth exceeded while calling a Python object"错误

python - 子进程调用失败

python - 通过子进程通过 python 运行 TCL,但不给出任何输出

Python,无法在 Windows 中使用 Ctrl-C 中断子进程