我正在通过python脚本编写qemu qga命令,如下所示:
python cmd.py request:'{"execute": "guest-execute", "session": "4768", "arguments": {"commands": [{"command": "/bin/sh", "arguments": ["sh", "-c", "route | grep default | awk '{print $2}'"]}]}}'
但是param被解析为bellow,它从'{print $ 2}'中取出了json字符串:
['cmd.py', 'request:{"execute": "guest-execute", "session": "4768", "arguments": {"commands": [{"command": "/bin/sh", "arguments": ["sh", "-c", "route | grep default | awk {print', '}"]}]}}']
实际上我想要这个,awk {print'{print $2}'
是在vm中运行的shell命令,并且这种格式无法改变:
['cmd.py', 'request:{"execute": "guest-execute", "session": "4768", "arguments": {"commands": [{"command": "/bin/sh", "arguments": ["sh", "-c", "route | grep default | awk {print'{print $2}'}"]}]}}']
有可能吗?如果不可能,那就意味着我必须在cmd.py中手工构建json字符串?
谢谢〜
答案 0 :(得分:1)
您不小心在其他单引号中嵌入了单引号: 如果我遗漏了字符串的第一部分,您将获得以下内容:
request:'... | awk '{print $2}'"]}]}}'
shell将其视为三个部分,并尝试解析那里的$2
:
request:'... | awk '
{print $2}
'"]}]}}'
如果你想在其他单引号中嵌入单引号,你必须这样做:
echo 'This string contains '\'' <- an embedded quote'
所以在你的情况下,完整的命令应该是
python cmd.py request:'{"execute": "guest-execute", "session": "4768", "arguments": {"commands": [{"command": "/bin/sh", "arguments": ["sh", "-c", "route | grep default | awk '\''{print $2}'\''"]}]}}'