我使用paramiko ssh将文件放在远程计算机上,如下所示。
rl = str(""" {"run_list":["role[monitor_server]"]}""")
cmd = """sudo touch /etc/chef/first-boot.json;sudo su - -c 'echo "%s" >> /etc/chef/first-boot.json'""" % (rl)
ssh.exec_command(cmd)
但是,当我查看文件时,它看起来像这样。
{run_list:[role[monitor_server]]}
我需要它来看这个: { “run_list”:[ “作用[monitor_server]”]}
如何保留报价?
答案 0 :(得分:1)
尝试转义引号。这是具体的解决方案,但应该有效。
>>> rl = """ {"run_list":["role[monitor_server]"]}""".replace('"', '\\"')
>>> print """sudo touch /etc/chef/first-boot.json;sudo su - -c 'echo "%s" >> /etc/chef/first-boot.json'""" % (rl)
sudo touch /etc/chef/first-boot.json;sudo su - -c 'echo " {\"run_list\":[\"role[monitor_server]\"]}" >> /etc/chef/first-boot.json'
答案 1 :(得分:1)
引号需要转义一次以适合echo
命令的参数。这是双引号分隔的“弱转义”:每个"
都必须转义为\"
,您还必须担心\
,$
和{ {1}}。然后将结果放入`
命令的参数中,以单引号分隔的“强转义”。在这里,必须通过突破字符串来包含任何单引号字符,例如通过替换为su
。
嵌套转义很难做到正确,如果涉及'\''
,任何错误的后果似乎都是安全的可怕。不惜一切代价避免使用嵌套模板和模板shell命令。
可能更好的解决方案是su
,然后通过cat > /etc/chef/first-boot.json
返回的stdin
文件类对象来管理您希望存储的内容。无需担心逃避。
或者只是使用Paramiko的SFTPClient来传输文件。
(另外,第一行的exec_command
完全是多余的。)