How do I escape a string for a shell command in node?

前端 未结 6 1797
粉色の甜心
粉色の甜心 2020-12-01 05:04

In nodejs, the only way to execute external commands is via sys.exec(cmd). I\'d like to call an external command and give it data via stdin. In nodejs there does yet not app

6条回答
  •  有刺的猬
    2020-12-01 05:38

    I second the opinion of Will, whenever possible you should avoid escaping by hand and prefer spawn.

    However, in the case that escaping is unavoidable, for example if you need to use exec or you are executing a command through ssh. Then you can use base64 to pass safe characters to bash and rely on bash to escape the unknown.

    const dangerStr = 'bad stuff here'
    // base64 has safe characters [A-Za-z=0-9+/]
    const dangerBase64 = btoa(dangerStr)
    
    sys.exec(`echo "$(echo ${dangerBase64} | base64 -d)" | somecommand`)
    

    The explanation is the following:

    dangerBase64 is unknown but it does not contain unsafe characters in bash. Hence echo ${dangerBase64} will output what we want.

    Finally the double quote around $(echo ${dangerBase64} | base64 -d) escape the actual value passed by the user inside bash, which is safe and has the same value that the user wanted.

提交回复
热议问题