如何将python变量传递给sed的子进程?

时间:2018-07-09 19:51:03

标签: python bash sed

我正尝试向sed发送呼叫,但似乎它没有处理变量,但在我打印时看起来正确,但在呼叫中不正确

#!/usr/bin/python -tt
import json
from pprint import pprint
from subprocess import call


with open('admin_list.json') as data_file:    
    admins = json.load(data_file)

#pprint(data[0]["key"])
for admin in admins:
    #print(admin["name"])
    #print (" sudo sed, 1 a  ${"+admin['key']+"} /home/"+admin['name']+"/.ssh/authorized_keys")
    call(["sudo sed", "1 a  ${"+admin['key']+"} /home/"+admin['name']+"/.ssh/authorized_keys"])

OSError:[Errno 2]没有这样的文件或目录”

我已经更新了代码,但没有收到错误,但文件仍未更新

#!/usr/bin/python -tt
import json
import os
from pprint import pprint
from subprocess import call


with open('admin_list.json') as data_file:    
    admins = json.load(data_file)

#pprint(data[0]["key"])
for admin in admins:

    call(["sudo","sed", "1 a "+admin['key']+"","/home/"+admin['name']+"/.ssh/authorized_keys"])
    call(['cat','/home/'+admin["name"]+'/.ssh/authorized_keys'])

1 个答案:

答案 0 :(得分:2)

您必须正确分割参数,否则空格将按字面意义解释

这里有4个参数:

  • sudo
  • sed
  • sed的论点
  • 以管理员身份解析的文件

也不要依赖环境。变量,请事先对其进行评估(否则,您将需要shell=True

因此将一个4项列表传递给call

call(["sudo","sed", "1 a  "+os.getenv(admin['key']),"/home/"+admin['name']+"/.ssh/authorized_keys"])

请注意,要就地修改文件,您需要向-i添加sed选项:

call(["sudo","sed", "-i", "1 a  "+os.getenv(admin['key']),"/home/"+admin['name']+"/.ssh/authorized_keys"])