繁体   English   中英

使用python变量执行Shell命令

[英]Execute a shell command with python variables

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

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

如何使用os.system在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))

使用子流程模块:

import subprocess
username = 'user'
result, err = subprocess.Popen(
            'su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"' % (username, username),
            stdout=subprocess.PIPE,
            shell=True
          ).communicate()
if err:
    print('Something went wrong')
else:
    print(result)

编辑:这是“快”的方式来做到这一点,你should't使用shell=True ,如果你无法控制的输入,因为它可以作为所述代码执行这里

os.system非常接近bash命令行,因为它使用了底层shell(例如其表亲subprocess.call ... using shell=True

在您的情况下,由于您的命令运行命令,因此subprocess的兴趣不大,因此您无法真正使用subprocess参数保护。

传递确切的命令,但是唯一的改变是保护简单的引号,否则python会认为这是字符串end + string start(您的字符串已经受到简单引号的保护),因此将其删除。

检查以下简单示例:

>>> 'hello '' world'
'hello  world'
>>> 'hello \'\' world'
"hello '' world"

当您无法使用双引号或简单引号来保护字符串(因为您正在使用其中的其他样式)时,这是最坏的情况。 在这种情况下,请使用\\转义引号:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM